comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
yeah. it's redundant.
public void transferBodyTo(WritableByteChannel channel) throws IOException { Objects.requireNonNull(channel, "'channel' must not be null"); Flux<ByteBuffer> body = getBody(); if (body != null) { FluxUtil.writeToWritableByteChannel(body, channel).block(); } }
Objects.requireNonNull(channel, "'channel' must not be null");
public void transferBodyTo(WritableByteChannel channel) throws IOException { Flux<ByteBuffer> body = getBody(); if (body != null) { FluxUtil.writeToWritableByteChannel(body, channel).block(); } }
class HttpResponse implements Closeable { private final HttpRequest request; /** * Creates an instance of {@link HttpResponse}. * * @param request The {@link HttpRequest} that resulted in this {@link HttpResponse}. */ protected HttpResponse(HttpRequest request) { this.request = request; } /** * Get the response status code. * * @return The response status code */ public abstract int getStatusCode(); /** * Lookup a response header with the provided name. * * @param name the name of the header to lookup. * @return the value of the header, or null if the header doesn't exist in the response. */ public abstract String getHeaderValue(String name); /** * Get all response headers. * * @return the response headers */ public abstract HttpHeaders getHeaders(); /** * Get the publisher emitting response content chunks. * <p> * Returns a stream of the response's body content. Emissions may occur on Reactor threads which should not be * blocked. Blocking should be avoided as much as possible/practical in reactive programming but if you do use * methods like {@code block()} on the stream then be sure to use {@code publishOn} before the blocking call. * * @return The response's content as a stream of {@link ByteBuffer}. */ public abstract Flux<ByteBuffer> getBody(); /** * Gets the {@link BinaryData} that represents the body of the response. * * Subclasses should override this method. * * @return The {@link BinaryData} response body. */ public BinaryData getBodyAsBinaryData() { Flux<ByteBuffer> body = getBody(); if (body != null) { return BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body)); } else { return null; } } /** * Gets the response content as a {@code byte[]}. * * @return The response content as a {@code byte[]}. */ public abstract Mono<byte[]> getBodyAsByteArray(); /** * Gets the response content as a {@link String}. * <p> * By default this method will inspect the response body for containing a byte order mark (BOM) to determine the * encoding of the string (UTF-8, UTF-16, etc.). If a BOM isn't found this will default to using UTF-8 as the * encoding, if a specific encoding is required use {@link * * @return The response content as a {@link String}. */ public abstract Mono<String> getBodyAsString(); /** * Gets the response content as a {@link String}. * * @param charset The {@link Charset} to use as the string encoding. * @return The response content as a {@link String}. */ public abstract Mono<String> getBodyAsString(Charset charset); /** * Gets the response content as an {@link InputStream}. * * @return The response content as an {@link InputStream}. */ public Mono<InputStream> getBodyAsInputStream() { return getBodyAsByteArray().map(ByteArrayInputStream::new); } /** * Gets the {@link HttpRequest request} which resulted in this response. * * @return The {@link HttpRequest request} which resulted in this response. */ public final HttpRequest getRequest() { return request; } /** * Gets a new {@link HttpResponse response} object wrapping this response with its content buffered into memory. * * @return A new {@link HttpResponse response} with the content buffered. */ public HttpResponse buffer() { return new BufferedHttpResponse(this); } /** * Transfers body bytes to the {@link AsynchronousByteChannel}. * @param channel The destination {@link AsynchronousByteChannel}. * @return A {@link Mono} that completes when transfer is completed. * @throws NullPointerException When {@code channel} is null. */ public Mono<Void> transferBodyToAsync(AsynchronousByteChannel channel) { Objects.requireNonNull(channel, "'channel' must not be null"); Flux<ByteBuffer> body = getBody(); if (body != null) { return FluxUtil.writeToAsynchronousByteChannel(body, channel); } else { return Mono.empty(); } } /** * Transfers body bytes to the {@link WritableByteChannel}. * @param channel The destination {@link WritableByteChannel}. * @throws IOException When I/O operation fails. * @throws NullPointerException When {@code channel} is null. */ /** * Closes the response content stream, if any. */ @Override public void close() { } }
class HttpResponse implements Closeable { private final HttpRequest request; /** * Creates an instance of {@link HttpResponse}. * * @param request The {@link HttpRequest} that resulted in this {@link HttpResponse}. */ protected HttpResponse(HttpRequest request) { this.request = request; } /** * Get the response status code. * * @return The response status code */ public abstract int getStatusCode(); /** * Lookup a response header with the provided name. * * @param name the name of the header to lookup. * @return the value of the header, or null if the header doesn't exist in the response. */ public abstract String getHeaderValue(String name); /** * Get all response headers. * * @return the response headers */ public abstract HttpHeaders getHeaders(); /** * Get the publisher emitting response content chunks. * <p> * Returns a stream of the response's body content. Emissions may occur on Reactor threads which should not be * blocked. Blocking should be avoided as much as possible/practical in reactive programming but if you do use * methods like {@code block()} on the stream then be sure to use {@code publishOn} before the blocking call. * * @return The response's content as a stream of {@link ByteBuffer}. */ public abstract Flux<ByteBuffer> getBody(); /** * Gets the {@link BinaryData} that represents the body of the response. * * Subclasses should override this method. * * @return The {@link BinaryData} response body. */ public BinaryData getBodyAsBinaryData() { Flux<ByteBuffer> body = getBody(); if (body != null) { return BinaryDataHelper.createBinaryData(new FluxByteBufferContent(body)); } else { return null; } } /** * Gets the response content as a {@code byte[]}. * * @return The response content as a {@code byte[]}. */ public abstract Mono<byte[]> getBodyAsByteArray(); /** * Gets the response content as a {@link String}. * <p> * By default this method will inspect the response body for containing a byte order mark (BOM) to determine the * encoding of the string (UTF-8, UTF-16, etc.). If a BOM isn't found this will default to using UTF-8 as the * encoding, if a specific encoding is required use {@link * * @return The response content as a {@link String}. */ public abstract Mono<String> getBodyAsString(); /** * Gets the response content as a {@link String}. * * @param charset The {@link Charset} to use as the string encoding. * @return The response content as a {@link String}. */ public abstract Mono<String> getBodyAsString(Charset charset); /** * Gets the response content as an {@link InputStream}. * * @return The response content as an {@link InputStream}. */ public Mono<InputStream> getBodyAsInputStream() { return getBodyAsByteArray().map(ByteArrayInputStream::new); } /** * Gets the {@link HttpRequest request} which resulted in this response. * * @return The {@link HttpRequest request} which resulted in this response. */ public final HttpRequest getRequest() { return request; } /** * Gets a new {@link HttpResponse response} object wrapping this response with its content buffered into memory. * * @return A new {@link HttpResponse response} with the content buffered. */ public HttpResponse buffer() { return new BufferedHttpResponse(this); } /** * Transfers body bytes to the {@link AsynchronousByteChannel}. * @param channel The destination {@link AsynchronousByteChannel}. * @return A {@link Mono} that completes when transfer is completed. * @throws NullPointerException When {@code channel} is null. */ public Mono<Void> transferBodyToAsync(AsynchronousByteChannel channel) { Objects.requireNonNull(channel, "'channel' must not be null"); Flux<ByteBuffer> body = getBody(); if (body != null) { return FluxUtil.writeToAsynchronousByteChannel(body, channel); } else { return Mono.empty(); } } /** * Transfers body bytes to the {@link WritableByteChannel}. * @param channel The destination {@link WritableByteChannel}. * @throws IOException When I/O operation fails. * @throws NullPointerException When {@code channel} is null. */ /** * Closes the response content stream, if any. */ @Override public void close() { } }
Good catch. I'll fix and add test.
public void completed(Integer result, ByteBuffer attachment) { try { transferAsynchronously(source, destination, buffer, sink); } catch (IOException e) { sink.error(e); } }
transferAsynchronously(source, destination, buffer, sink);
public void completed(Integer result, ByteBuffer attachment) { try { if (buffer.hasRemaining()) { destination.write(buffer, buffer, this); } else { transferAsynchronously(source, destination, buffer, sink); } } catch (IOException e) { sink.error(e); } }
class IOUtils { private static final ClientLogger LOGGER = new ClientLogger(IOUtils.class); private static final int DEFAULT_BUFFER_SIZE = 8192; /** * Adapts {@link AsynchronousFileChannel} to {@link AsynchronousByteChannel}. * @param fileChannel The {@link AsynchronousFileChannel}. * @param position The position in the file to begin writing or reading the {@code content}. * @return A {@link AsynchronousByteChannel} that delegates to {@code fileChannel}. * @throws NullPointerException When {@code fileChannel} is null. * @throws IllegalArgumentException When {@code position} is negative. */ public static AsynchronousByteChannel toAsynchronousByteChannel( AsynchronousFileChannel fileChannel, long position) { Objects.requireNonNull(fileChannel, "'fileChannel' must not be null"); if (position < 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'position' cannot be less than 0.")); } return new AsynchronousFileChannelAdapter(fileChannel, position); } /** * Transfers bytes from {@link ReadableByteChannel} to {@link WritableByteChannel}. * @param source A source {@link ReadableByteChannel}. * @param destination A destination {@link WritableByteChannel}. * @throws IOException When I/O operation fails. * @throws NullPointerException When {@code source} is null. * @throws NullPointerException When {@code destination} is null. */ public static void transfer(ReadableByteChannel source, WritableByteChannel destination) throws IOException { Objects.requireNonNull(source, "'source' must not be null"); Objects.requireNonNull(source, "'destination' must not be null"); ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); int read; do { buffer.clear(); read = source.read(buffer); buffer.flip(); while (buffer.hasRemaining()) { destination.write(buffer); } } while (read >= 0); } /** * Transfers bytes from {@link ReadableByteChannel} to {@link AsynchronousByteChannel}. * @param source A source {@link ReadableByteChannel}. * @param destination A destination {@link AsynchronousByteChannel}. * @return A {@link Mono} that completes when transfer is finished. * @throws NullPointerException When {@code source} is null. * @throws NullPointerException When {@code destination} is null. */ public static Mono<Void> transferAsync(ReadableByteChannel source, AsynchronousByteChannel destination) { Objects.requireNonNull(source, "'source' must not be null"); Objects.requireNonNull(source, "'destination' must not be null"); return Mono.create(sink -> sink.onRequest(value -> { ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); try { transferAsynchronously(source, destination, buffer, sink); } catch (IOException e) { sink.error(e); } })); } private static void transferAsynchronously( ReadableByteChannel source, AsynchronousByteChannel destination, ByteBuffer buffer, MonoSink<Void> sink) throws IOException { buffer.clear(); int read = source.read(buffer); if (read >= 0) { buffer.flip(); destination.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override @Override public void failed(Throwable e, ByteBuffer attachment) { sink.error(e); } }); } else { sink.success(); } } }
class IOUtils { private static final ClientLogger LOGGER = new ClientLogger(IOUtils.class); private static final int DEFAULT_BUFFER_SIZE = 8192; /** * Adapts {@link AsynchronousFileChannel} to {@link AsynchronousByteChannel}. * @param fileChannel The {@link AsynchronousFileChannel}. * @param position The position in the file to begin writing or reading the {@code content}. * @return A {@link AsynchronousByteChannel} that delegates to {@code fileChannel}. * @throws NullPointerException When {@code fileChannel} is null. * @throws IllegalArgumentException When {@code position} is negative. */ public static AsynchronousByteChannel toAsynchronousByteChannel( AsynchronousFileChannel fileChannel, long position) { Objects.requireNonNull(fileChannel, "'fileChannel' must not be null"); if (position < 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'position' cannot be less than 0.")); } return new AsynchronousFileChannelAdapter(fileChannel, position); } /** * Transfers bytes from {@link ReadableByteChannel} to {@link WritableByteChannel}. * @param source A source {@link ReadableByteChannel}. * @param destination A destination {@link WritableByteChannel}. * @throws IOException When I/O operation fails. * @throws NullPointerException When {@code source} is null. * @throws NullPointerException When {@code destination} is null. */ public static void transfer(ReadableByteChannel source, WritableByteChannel destination) throws IOException { Objects.requireNonNull(source, "'source' must not be null"); Objects.requireNonNull(source, "'destination' must not be null"); ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); int read; do { buffer.clear(); read = source.read(buffer); buffer.flip(); while (buffer.hasRemaining()) { destination.write(buffer); } } while (read >= 0); } /** * Transfers bytes from {@link ReadableByteChannel} to {@link AsynchronousByteChannel}. * @param source A source {@link ReadableByteChannel}. * @param destination A destination {@link AsynchronousByteChannel}. * @return A {@link Mono} that completes when transfer is finished. * @throws NullPointerException When {@code source} is null. * @throws NullPointerException When {@code destination} is null. */ public static Mono<Void> transferAsync(ReadableByteChannel source, AsynchronousByteChannel destination) { Objects.requireNonNull(source, "'source' must not be null"); Objects.requireNonNull(source, "'destination' must not be null"); return Mono.create(sink -> sink.onRequest(value -> { ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); try { transferAsynchronously(source, destination, buffer, sink); } catch (IOException e) { sink.error(e); } })); } private static void transferAsynchronously( ReadableByteChannel source, AsynchronousByteChannel destination, ByteBuffer buffer, MonoSink<Void> sink) throws IOException { buffer.clear(); int read = source.read(buffer); if (read >= 0) { buffer.flip(); destination.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override @Override public void failed(Throwable e, ByteBuffer attachment) { sink.error(e); } }); } else { sink.success(); } } }
have to check what if happens if you pass null
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofMinutes(60))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofMinutes(1440))); return argumentsList.stream(); }
List<Arguments> argumentsList = new ArrayList<>();
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofHours(1))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofHours(24))); argumentsList.add(Arguments.of("NullExpiration", null)); return argumentsList.stream(); }
class TokenCustomExpirationTimeHelper { static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } }
class TokenCustomExpirationTimeHelper { private static final double TOKEN_EXPIRATION_ALLOWED_DEVIATION = 0.05; private static final int MAX_TOKEN_EXPIRATION_IN_MINUTES = 1440; static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } static void assertTokenExpirationWithinAllowedDeviation(Duration expectedTokenExpiration, OffsetDateTime tokenExpiresIn) { if (getTestMode() != TestMode.PLAYBACK) { Duration expectedExpiration = expectedTokenExpiration == null ? Duration.ofDays(1) : expectedTokenExpiration; OffsetDateTime utcDateTimeNow = OffsetDateTime.now(Clock.systemUTC()); long tokenSeconds = ChronoUnit.SECONDS.between(utcDateTimeNow, tokenExpiresIn); long expectedTime = expectedExpiration.getSeconds(); long timeDiff = Math.abs(expectedTime - tokenSeconds); double allowedTimeDiff = expectedTime * TOKEN_EXPIRATION_ALLOWED_DEVIATION; assertTrue(timeDiff < allowedTimeDiff, getTokenExpirationOutsideAllowedDeviationErrorMessage(expectedTokenExpiration, tokenSeconds)); } } private static String getTokenExpirationOutsideAllowedDeviationErrorMessage(Duration tokenExpiresIn, long actualExpiration) { long tokenExpiresInMinutes = tokenExpiresIn == null ? MAX_TOKEN_EXPIRATION_IN_MINUTES : tokenExpiresIn.getSeconds() / 60; double actualExpirationInMinutes = actualExpiration / 60; return String.format("Token expiration is outside of allowed %d%% deviation. Expected minutes: %d, actual minutes: %s", (int) (TOKEN_EXPIRATION_ALLOWED_DEVIATION * 100), tokenExpiresInMinutes, Math.round(actualExpirationInMinutes * 100) / 100); } }
why do not go with hours? :)
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofMinutes(60))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofMinutes(1440))); return argumentsList.stream(); }
argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofMinutes(60)));
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofHours(1))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofHours(24))); argumentsList.add(Arguments.of("NullExpiration", null)); return argumentsList.stream(); }
class TokenCustomExpirationTimeHelper { static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } }
class TokenCustomExpirationTimeHelper { private static final double TOKEN_EXPIRATION_ALLOWED_DEVIATION = 0.05; private static final int MAX_TOKEN_EXPIRATION_IN_MINUTES = 1440; static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } static void assertTokenExpirationWithinAllowedDeviation(Duration expectedTokenExpiration, OffsetDateTime tokenExpiresIn) { if (getTestMode() != TestMode.PLAYBACK) { Duration expectedExpiration = expectedTokenExpiration == null ? Duration.ofDays(1) : expectedTokenExpiration; OffsetDateTime utcDateTimeNow = OffsetDateTime.now(Clock.systemUTC()); long tokenSeconds = ChronoUnit.SECONDS.between(utcDateTimeNow, tokenExpiresIn); long expectedTime = expectedExpiration.getSeconds(); long timeDiff = Math.abs(expectedTime - tokenSeconds); double allowedTimeDiff = expectedTime * TOKEN_EXPIRATION_ALLOWED_DEVIATION; assertTrue(timeDiff < allowedTimeDiff, getTokenExpirationOutsideAllowedDeviationErrorMessage(expectedTokenExpiration, tokenSeconds)); } } private static String getTokenExpirationOutsideAllowedDeviationErrorMessage(Duration tokenExpiresIn, long actualExpiration) { long tokenExpiresInMinutes = tokenExpiresIn == null ? MAX_TOKEN_EXPIRATION_IN_MINUTES : tokenExpiresIn.getSeconds() / 60; double actualExpirationInMinutes = actualExpiration / 60; return String.format("Token expiration is outside of allowed %d%% deviation. Expected minutes: %d, actual minutes: %s", (int) (TOKEN_EXPIRATION_ALLOWED_DEVIATION * 100), tokenExpiresInMinutes, Math.round(actualExpirationInMinutes * 100) / 100); } }
Added case for null.
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofMinutes(60))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofMinutes(1440))); return argumentsList.stream(); }
List<Arguments> argumentsList = new ArrayList<>();
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofHours(1))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofHours(24))); argumentsList.add(Arguments.of("NullExpiration", null)); return argumentsList.stream(); }
class TokenCustomExpirationTimeHelper { static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } }
class TokenCustomExpirationTimeHelper { private static final double TOKEN_EXPIRATION_ALLOWED_DEVIATION = 0.05; private static final int MAX_TOKEN_EXPIRATION_IN_MINUTES = 1440; static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } static void assertTokenExpirationWithinAllowedDeviation(Duration expectedTokenExpiration, OffsetDateTime tokenExpiresIn) { if (getTestMode() != TestMode.PLAYBACK) { Duration expectedExpiration = expectedTokenExpiration == null ? Duration.ofDays(1) : expectedTokenExpiration; OffsetDateTime utcDateTimeNow = OffsetDateTime.now(Clock.systemUTC()); long tokenSeconds = ChronoUnit.SECONDS.between(utcDateTimeNow, tokenExpiresIn); long expectedTime = expectedExpiration.getSeconds(); long timeDiff = Math.abs(expectedTime - tokenSeconds); double allowedTimeDiff = expectedTime * TOKEN_EXPIRATION_ALLOWED_DEVIATION; assertTrue(timeDiff < allowedTimeDiff, getTokenExpirationOutsideAllowedDeviationErrorMessage(expectedTokenExpiration, tokenSeconds)); } } private static String getTokenExpirationOutsideAllowedDeviationErrorMessage(Duration tokenExpiresIn, long actualExpiration) { long tokenExpiresInMinutes = tokenExpiresIn == null ? MAX_TOKEN_EXPIRATION_IN_MINUTES : tokenExpiresIn.getSeconds() / 60; double actualExpirationInMinutes = actualExpiration / 60; return String.format("Token expiration is outside of allowed %d%% deviation. Expected minutes: %d, actual minutes: %s", (int) (TOKEN_EXPIRATION_ALLOWED_DEVIATION * 100), tokenExpiresInMinutes, Math.round(actualExpirationInMinutes * 100) / 100); } }
Updated :-)
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofMinutes(60))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofMinutes(1440))); return argumentsList.stream(); }
argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofMinutes(60)));
static Stream<Arguments> getValidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MinValidCustomExpiration", Duration.ofHours(1))); argumentsList.add(Arguments.of("MaxValidCustomExpiration", Duration.ofHours(24))); argumentsList.add(Arguments.of("NullExpiration", null)); return argumentsList.stream(); }
class TokenCustomExpirationTimeHelper { static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } }
class TokenCustomExpirationTimeHelper { private static final double TOKEN_EXPIRATION_ALLOWED_DEVIATION = 0.05; private static final int MAX_TOKEN_EXPIRATION_IN_MINUTES = 1440; static Stream<Arguments> getInvalidExpirationTimes() { List<Arguments> argumentsList = new ArrayList<>(); argumentsList.add(Arguments.of("MaxInvalidCustomExpiration", Duration.ofMinutes(59))); argumentsList.add(Arguments.of("MinInvalidCustomExpiration", Duration.ofMinutes(1441))); return argumentsList.stream(); } static void assertTokenExpirationWithinAllowedDeviation(Duration expectedTokenExpiration, OffsetDateTime tokenExpiresIn) { if (getTestMode() != TestMode.PLAYBACK) { Duration expectedExpiration = expectedTokenExpiration == null ? Duration.ofDays(1) : expectedTokenExpiration; OffsetDateTime utcDateTimeNow = OffsetDateTime.now(Clock.systemUTC()); long tokenSeconds = ChronoUnit.SECONDS.between(utcDateTimeNow, tokenExpiresIn); long expectedTime = expectedExpiration.getSeconds(); long timeDiff = Math.abs(expectedTime - tokenSeconds); double allowedTimeDiff = expectedTime * TOKEN_EXPIRATION_ALLOWED_DEVIATION; assertTrue(timeDiff < allowedTimeDiff, getTokenExpirationOutsideAllowedDeviationErrorMessage(expectedTokenExpiration, tokenSeconds)); } } private static String getTokenExpirationOutsideAllowedDeviationErrorMessage(Duration tokenExpiresIn, long actualExpiration) { long tokenExpiresInMinutes = tokenExpiresIn == null ? MAX_TOKEN_EXPIRATION_IN_MINUTES : tokenExpiresIn.getSeconds() / 60; double actualExpirationInMinutes = actualExpiration / 60; return String.format("Token expiration is outside of allowed %d%% deviation. Expected minutes: %d, actual minutes: %s", (int) (TOKEN_EXPIRATION_ALLOWED_DEVIATION * 100), tokenExpiresInMinutes, Math.round(actualExpirationInMinutes * 100) / 100); } }
```suggestion asyncClient = setupAsyncClient(builder, "createUserAndTokenWithValidCustomExpiration " + testName); ``` for test logs readability :)
public void createUserAndTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithValidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getUserToken().getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); }
asyncClient = setupAsyncClient(builder, "createUserAndTokenWithValidCustomExpiration" + testName);
public void createUserAndTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithValidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getUserToken().getExpiresAt()); }) .verifyComplete(); }
class CommunicationIdentityAsyncTests extends CommunicationIdentityClientTestBase { private CommunicationIdentityAsyncClient asyncClient; @Test public void createAsyncIdentityClientUsingConnectionString() { CommunicationIdentityClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); asyncClient = setupAsyncClient(builder, "createAsyncIdentityClientUsingConnectionString"); assertNotNull(asyncClient); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); assertFalse(item.getId().isEmpty()); }) .verifyComplete(); } @Test public void createUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUser"); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); }) .verifyComplete(); } @Test public void createUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserWithResponse"); Mono<Response<CommunicationUserIdentifier>> response = asyncClient.createUserWithResponse(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getValue().getId()); assertFalse(item.getValue().getId().isEmpty()); assertEquals(201, item.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @Test public void createUserAndToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndToken"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithInvalidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithValidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getValue().getUserToken().getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithInvalidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void createUserAndTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponse"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); }) .verifyComplete(); } @Test public void createUserAndTokenNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenNullScopes"); StepVerifier.create( asyncClient.createUserAndToken(null)) .verifyError(NullPointerException.class); } @Test public void createUserAndTokenWithResponseNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseNullScopes"); StepVerifier.create( asyncClient.createUserAndTokenWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void deleteUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUser"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUser(communicationUser); })) .verifyComplete(); } @Test public void deleteUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUserWithResponse(communicationUser); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void deleteUserWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithNullUser"); StepVerifier.create( asyncClient.deleteUser(null)) .verifyError(NullPointerException.class); } @Test public void deleteUserWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponseWithNullUser"); StepVerifier.create( asyncClient.deleteUserWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void revokeToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeToken"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokens(communicationUser); }); })) .verifyComplete(); } @Test public void revokeTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokensWithResponse(communicationUser); }); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void revokeTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithNullUser"); StepVerifier.create( asyncClient.revokeTokens(null)) .verifyError(NullPointerException.class); } @Test public void revokeTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponseWithNullUser"); StepVerifier.create( asyncClient.revokeTokensWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void getToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getToken"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes); })) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithValidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithInvalidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithValidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getValue().getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithInvalidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void getTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); }) .verifyComplete(); } @Test public void getTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getToken(null, scopes)) .verifyError(NullPointerException.class); } @Test public void getTokenWithNullScope() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullScope"); StepVerifier.create(asyncClient.getToken(new CommunicationUserIdentifier("testUser"), null)) .verifyError(NullPointerException.class); } @Test public void getTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getTokenWithResponse(null, scopes)) .verifyError(NullPointerException.class); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParams(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParams"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParamsWithResponse(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParamsWithResponse"); Mono<Response<AccessToken>> response = asyncClient.getTokenForTeamsUserWithResponse(options); StepVerifier.create(response) .assertNext(issuedTokenResponse -> { verifyTokenNotEmpty(issuedTokenResponse.getValue()); assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @ParameterizedTest(name = "when {3} is null") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithNullParams(GetTokenForTeamsUserOptions options, String exceptionMessage) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithNull:when " + exceptionMessage + " is null"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains(exceptionMessage)); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidToken(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("401")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidAppId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidUserId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } }
class CommunicationIdentityAsyncTests extends CommunicationIdentityClientTestBase { private CommunicationIdentityAsyncClient asyncClient; @Test public void createAsyncIdentityClientUsingConnectionString() { CommunicationIdentityClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); asyncClient = setupAsyncClient(builder, "createAsyncIdentityClientUsingConnectionString"); assertNotNull(asyncClient); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); assertFalse(item.getId().isEmpty()); }) .verifyComplete(); } @Test public void createUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUser"); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); }) .verifyComplete(); } @Test public void createUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserWithResponse"); Mono<Response<CommunicationUserIdentifier>> response = asyncClient.createUserWithResponse(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getValue().getId()); assertFalse(item.getValue().getId().isEmpty()); assertEquals(201, item.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @Test public void createUserAndToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndToken"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithInvalidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithValidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getValue().getUserToken().getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithInvalidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void createUserAndTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponse"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); }) .verifyComplete(); } @Test public void createUserAndTokenNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenNullScopes"); StepVerifier.create( asyncClient.createUserAndToken(null)) .verifyError(NullPointerException.class); } @Test public void createUserAndTokenWithResponseNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseNullScopes"); StepVerifier.create( asyncClient.createUserAndTokenWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void deleteUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUser"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUser(communicationUser); })) .verifyComplete(); } @Test public void deleteUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUserWithResponse(communicationUser); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void deleteUserWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithNullUser"); StepVerifier.create( asyncClient.deleteUser(null)) .verifyError(NullPointerException.class); } @Test public void deleteUserWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponseWithNullUser"); StepVerifier.create( asyncClient.deleteUserWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void revokeToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeToken"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokens(communicationUser); }); })) .verifyComplete(); } @Test public void revokeTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokensWithResponse(communicationUser); }); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void revokeTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithNullUser"); StepVerifier.create( asyncClient.revokeTokens(null)) .verifyError(NullPointerException.class); } @Test public void revokeTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponseWithNullUser"); StepVerifier.create( asyncClient.revokeTokensWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void getToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getToken"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes); })) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithValidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithInvalidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithValidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getValue().getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithInvalidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void getTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); }) .verifyComplete(); } @Test public void getTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getToken(null, scopes)) .verifyError(NullPointerException.class); } @Test public void getTokenWithNullScope() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullScope"); StepVerifier.create(asyncClient.getToken(new CommunicationUserIdentifier("testUser"), null)) .verifyError(NullPointerException.class); } @Test public void getTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getTokenWithResponse(null, scopes)) .verifyError(NullPointerException.class); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParams(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParams"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParamsWithResponse(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParamsWithResponse"); Mono<Response<AccessToken>> response = asyncClient.getTokenForTeamsUserWithResponse(options); StepVerifier.create(response) .assertNext(issuedTokenResponse -> { verifyTokenNotEmpty(issuedTokenResponse.getValue()); assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @ParameterizedTest(name = "when {3} is null") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithNullParams(GetTokenForTeamsUserOptions options, String exceptionMessage) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithNull:when " + exceptionMessage + " is null"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains(exceptionMessage)); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidToken(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("401")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidAppId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidUserId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } }
```suggestion asyncClient = setupAsyncClient(builder, "createUserAndTokenWithInvalidCustomExpiration " + testName); ``` for test logs readability :)
public void createUserAndTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithInvalidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); }
asyncClient = setupAsyncClient(builder, "createUserAndTokenWithInvalidCustomExpiration" + testName);
public void createUserAndTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithInvalidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); }
class CommunicationIdentityAsyncTests extends CommunicationIdentityClientTestBase { private CommunicationIdentityAsyncClient asyncClient; @Test public void createAsyncIdentityClientUsingConnectionString() { CommunicationIdentityClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); asyncClient = setupAsyncClient(builder, "createAsyncIdentityClientUsingConnectionString"); assertNotNull(asyncClient); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); assertFalse(item.getId().isEmpty()); }) .verifyComplete(); } @Test public void createUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUser"); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); }) .verifyComplete(); } @Test public void createUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserWithResponse"); Mono<Response<CommunicationUserIdentifier>> response = asyncClient.createUserWithResponse(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getValue().getId()); assertFalse(item.getValue().getId().isEmpty()); assertEquals(201, item.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @Test public void createUserAndToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndToken"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithValidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getUserToken().getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithValidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getValue().getUserToken().getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithInvalidCustomExpiration" + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void createUserAndTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponse"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); }) .verifyComplete(); } @Test public void createUserAndTokenNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenNullScopes"); StepVerifier.create( asyncClient.createUserAndToken(null)) .verifyError(NullPointerException.class); } @Test public void createUserAndTokenWithResponseNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseNullScopes"); StepVerifier.create( asyncClient.createUserAndTokenWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void deleteUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUser"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUser(communicationUser); })) .verifyComplete(); } @Test public void deleteUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUserWithResponse(communicationUser); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void deleteUserWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithNullUser"); StepVerifier.create( asyncClient.deleteUser(null)) .verifyError(NullPointerException.class); } @Test public void deleteUserWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponseWithNullUser"); StepVerifier.create( asyncClient.deleteUserWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void revokeToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeToken"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokens(communicationUser); }); })) .verifyComplete(); } @Test public void revokeTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokensWithResponse(communicationUser); }); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void revokeTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithNullUser"); StepVerifier.create( asyncClient.revokeTokens(null)) .verifyError(NullPointerException.class); } @Test public void revokeTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponseWithNullUser"); StepVerifier.create( asyncClient.revokeTokensWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void getToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getToken"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes); })) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithValidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithInvalidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithValidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); if (getTestMode() == TestMode.LIVE) { CommunicationIdentityClientUtils.TokenExpirationDeviationData tokenExpirationData = CommunicationIdentityClientUtils.tokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getValue().getExpiresAt()); assertTrue(tokenExpirationData.getIsWithinAllowedDeviation(), CommunicationIdentityClientUtils.getTokenExpirationOutsideAllowedDeviationErrorMessage(tokenExpiresIn, tokenExpirationData.getActualExpirationInSeconds()) ); } }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithInvalidCustomExpiration" + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void getTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); }) .verifyComplete(); } @Test public void getTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getToken(null, scopes)) .verifyError(NullPointerException.class); } @Test public void getTokenWithNullScope() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullScope"); StepVerifier.create(asyncClient.getToken(new CommunicationUserIdentifier("testUser"), null)) .verifyError(NullPointerException.class); } @Test public void getTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getTokenWithResponse(null, scopes)) .verifyError(NullPointerException.class); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParams(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParams"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParamsWithResponse(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParamsWithResponse"); Mono<Response<AccessToken>> response = asyncClient.getTokenForTeamsUserWithResponse(options); StepVerifier.create(response) .assertNext(issuedTokenResponse -> { verifyTokenNotEmpty(issuedTokenResponse.getValue()); assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @ParameterizedTest(name = "when {3} is null") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithNullParams(GetTokenForTeamsUserOptions options, String exceptionMessage) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithNull:when " + exceptionMessage + " is null"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains(exceptionMessage)); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidToken(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("401")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidAppId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidUserId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } }
class CommunicationIdentityAsyncTests extends CommunicationIdentityClientTestBase { private CommunicationIdentityAsyncClient asyncClient; @Test public void createAsyncIdentityClientUsingConnectionString() { CommunicationIdentityClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); asyncClient = setupAsyncClient(builder, "createAsyncIdentityClientUsingConnectionString"); assertNotNull(asyncClient); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); assertFalse(item.getId().isEmpty()); }) .verifyComplete(); } @Test public void createUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUser"); Mono<CommunicationUserIdentifier> response = asyncClient.createUser(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); }) .verifyComplete(); } @Test public void createUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserWithResponse"); Mono<Response<CommunicationUserIdentifier>> response = asyncClient.createUserWithResponse(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getValue().getId()); assertFalse(item.getValue().getId().isEmpty()); assertEquals(201, item.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @Test public void createUserAndToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndToken"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithValidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertNotNull(result.getUserToken()); assertNotNull(result.getUser()); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getUserToken().getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithValidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, result.getValue().getUserToken().getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void createUserAndTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithInvalidCustomExpiration " + testName); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void createUserAndTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<CommunicationUserIdentifierAndToken> createUserAndToken = asyncClient.createUserAndToken(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseWithOverflownCustomExpiration"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes, tokenExpiresIn); StepVerifier.create(createUserAndToken) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void createUserAndTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponse"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); Mono<Response<CommunicationUserIdentifierAndToken>> createUserAndToken = asyncClient.createUserAndTokenWithResponse(scopes); StepVerifier.create(createUserAndToken) .assertNext(result -> { assertEquals(201, result.getStatusCode()); assertNotNull(result.getValue().getUserToken()); assertNotNull(result.getValue().getUser()); }) .verifyComplete(); } @Test public void createUserAndTokenNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenNullScopes"); StepVerifier.create( asyncClient.createUserAndToken(null)) .verifyError(NullPointerException.class); } @Test public void createUserAndTokenWithResponseNullScopes() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "createUserAndTokenWithResponseNullScopes"); StepVerifier.create( asyncClient.createUserAndTokenWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void deleteUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUser"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUser(communicationUser); })) .verifyComplete(); } @Test public void deleteUserWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { return asyncClient.deleteUserWithResponse(communicationUser); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void deleteUserWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithNullUser"); StepVerifier.create( asyncClient.deleteUser(null)) .verifyError(NullPointerException.class); } @Test public void deleteUserWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "deleteUserWithResponseWithNullUser"); StepVerifier.create( asyncClient.deleteUserWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void revokeToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeToken"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokens(communicationUser); }); })) .verifyComplete(); } @Test public void revokeTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap((CommunicationUserIdentifier communicationUser) -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes) .flatMap((AccessToken communicationUserToken) -> { return asyncClient.revokeTokensWithResponse(communicationUser); }); })) .assertNext(item -> { assertEquals(204, item.getStatusCode(), "Expect status code to be 204"); }) .verifyComplete(); } @Test public void revokeTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithNullUser"); StepVerifier.create( asyncClient.revokeTokens(null)) .verifyError(NullPointerException.class); } @Test public void revokeTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "revokeTokenWithResponseWithNullUser"); StepVerifier.create( asyncClient.revokeTokensWithResponse(null)) .verifyError(NullPointerException.class); } @Test public void getToken() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getToken"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes); })) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithValidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithInvalidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithValidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithValidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); assertTokenExpirationWithinAllowedDeviation(tokenExpiresIn, issuedToken.getValue().getExpiresAt()); }) .verifyComplete(); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.TokenCustomExpirationTimeHelper public void getTokenWithResponseWithInvalidCustomExpiration(String testName, Duration tokenExpiresIn) { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithInvalidCustomExpiration " + testName); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @Test public void getTokenWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getToken(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponseWithOverflownCustomExpiration() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithOverflownCustomExpiration"); Duration tokenExpiresIn = Duration.ofDays(Integer.MAX_VALUE); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes, tokenExpiresIn); })) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof IllegalArgumentException); assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().equals(CommunicationIdentityClientUtils.TOKEN_EXPIRATION_OVERFLOW_MESSAGE)); }); } @Test public void getTokenWithResponse() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponse"); StepVerifier.create( asyncClient.createUser() .flatMap(communicationUser -> { List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); return asyncClient.getTokenWithResponse(communicationUser, scopes); })) .assertNext(issuedToken -> { verifyTokenNotEmpty(issuedToken.getValue()); assertEquals(issuedToken.getStatusCode(), 200); }) .verifyComplete(); } @Test public void getTokenWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getToken(null, scopes)) .verifyError(NullPointerException.class); } @Test public void getTokenWithNullScope() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithNullScope"); StepVerifier.create(asyncClient.getToken(new CommunicationUserIdentifier("testUser"), null)) .verifyError(NullPointerException.class); } @Test public void getTokenWithResponseWithNullUser() { CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenWithResponseWithNullUser"); List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT); StepVerifier.create( asyncClient.getTokenWithResponse(null, scopes)) .verifyError(NullPointerException.class); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParams(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParams"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .assertNext(issuedToken -> verifyTokenNotEmpty(issuedToken)) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithValidParamsWithResponse(GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithValidParamsWithResponse"); Mono<Response<AccessToken>> response = asyncClient.getTokenForTeamsUserWithResponse(options); StepVerifier.create(response) .assertNext(issuedTokenResponse -> { verifyTokenNotEmpty(issuedTokenResponse.getValue()); assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 201"); }) .verifyComplete(); } @ParameterizedTest(name = "when {3} is null") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithNullParams(GetTokenForTeamsUserOptions options, String exceptionMessage) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, "getTokenForTeamsUserWithNull:when " + exceptionMessage + " is null"); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains(exceptionMessage)); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidToken(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("401")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidAppId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } @ParameterizedTest(name = "{0}") @MethodSource("com.azure.communication.identity.CteTestHelper public void getTokenForTeamsUserWithInvalidUserId(String testName, GetTokenForTeamsUserOptions options) { if (skipExchangeAadTeamsTokenTest()) { return; } CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient); asyncClient = setupAsyncClient(builder, testName); Mono<AccessToken> response = asyncClient.getTokenForTeamsUser(options); StepVerifier.create(response) .verifyErrorSatisfies(throwable -> { assertNotNull(throwable.getMessage()); assertTrue(throwable.getMessage().contains("400")); }); } }
why set rgName2 = null here?
public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); }
rgName2 = null;
public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
we only use rgName in this test. just a hack so clean-up know it does not need to delete rgName2 resource group
public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); }
rgName2 = null;
public void canCRUDLinuxFunctionAppJava17() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_17) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_17); assertRunning(functionApp1); }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
class FunctionAppsTests extends AppServiceTest { private String rgName1 = ""; private String rgName2 = ""; private String webappName1 = ""; private String webappName2 = ""; private String webappName3 = ""; private String appServicePlanName1 = ""; private String appServicePlanName2 = ""; private String storageAccountName1 = ""; protected StorageManager storageManager; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { webappName1 = generateRandomResourceName("java-func-", 20); webappName2 = generateRandomResourceName("java-func-", 20); webappName3 = generateRandomResourceName("java-func-", 20); appServicePlanName1 = generateRandomResourceName("java-asp-", 20); appServicePlanName2 = generateRandomResourceName("java-asp-", 20); storageAccountName1 = generateRandomResourceName("javastore", 20); rgName1 = generateRandomResourceName("javacsmrg", 20); rgName2 = generateRandomResourceName("javacsmrg", 20); storageManager = buildManager(StorageManager.class, httpPipeline, profile); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { if (rgName1 != null) { resourceManager.resourceGroups().beginDeleteByName(rgName1); } if (rgName2 != null) { try { resourceManager.resourceGroups().beginDeleteByName(rgName2); } catch (ManagementException e) { } } } @Test public void canCRUDFunctionApp() throws Exception { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName1) .create(); Assertions.assertNotNull(functionApp1); Assertions.assertEquals(Region.US_WEST, functionApp1.region()); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_WEST, plan1.region()); Assertions.assertEquals(new PricingTier("Dynamic", "Y1"), plan1.pricingTier()); FunctionAppResource functionAppResource1 = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource1.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.storageAccount.getKeys().get(0).value(), functionAppResource1.accountKey); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withExistingAppServicePlan(plan1) .withNewResourceGroup(rgName2) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName2) .withNewAppServicePlan(PricingTier.BASIC_B1) .withExistingStorageAccount(functionApp1.storageAccount()) .create(); Assertions.assertNotNull(functionApp2); Assertions.assertEquals(Region.US_WEST, functionApp2.region()); FunctionAppResource functionAppResource3 = getStorageAccount(storageManager, functionApp3); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertFalse(functionAppResource3.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource3.storageAccount.getKeys().get(0).value(), functionAppResource3.accountKey); FunctionApp functionApp = appServiceManager.functionApps().getByResourceGroup(rgName1, functionApp1.name()); Assertions.assertEquals(functionApp1.id(), functionApp.id()); functionApp = appServiceManager.functionApps().getById(functionApp2.id()); Assertions.assertEquals(functionApp2.name(), functionApp.name()); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); functionApps = appServiceManager.functionApps().listByResourceGroup(rgName2); Assertions.assertEquals(2, TestUtilities.getSize(functionApps)); functionApp2.update().withNewStorageAccount(storageAccountName1, StorageAccountSkuType.STANDARD_LRS).apply(); Assertions.assertEquals(storageAccountName1, functionApp2.storageAccount().name()); FunctionAppResource functionAppResource2 = getStorageAccount(storageManager, functionApp2); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING)); Assertions.assertTrue(functionAppResource2.appSettings.containsKey(KEY_CONTENT_SHARE)); Assertions .assertEquals( functionAppResource2.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource2.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions.assertEquals(storageAccountName1, functionAppResource2.storageAccount.name()); Assertions .assertEquals( functionAppResource2.storageAccount.getKeys().get(0).value(), functionAppResource2.accountKey); int numStorageAccountBefore = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); functionApp1.update().withAppSetting("newKey", "newValue").apply(); int numStorageAccountAfter = TestUtilities.getSize(storageManager.storageAccounts().listByResourceGroup(rgName1)); Assertions.assertEquals(numStorageAccountBefore, numStorageAccountAfter); FunctionAppResource functionAppResource1Updated = getStorageAccount(storageManager, functionApp1); Assertions.assertTrue(functionAppResource1Updated.appSettings.containsKey("newKey")); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(), functionAppResource1Updated.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_AZURE_FILE_CONNECTION_STRING).value()); Assertions .assertEquals( functionAppResource1.appSettings.get(KEY_CONTENT_SHARE).value(), functionAppResource1Updated.appSettings.get(KEY_CONTENT_SHARE).value()); Assertions .assertEquals( functionAppResource1.storageAccount.name(), functionAppResource1Updated.storageAccount.name()); functionApp3.update().withNewAppServicePlan(PricingTier.STANDARD_S2).apply(); Assertions.assertNotEquals(functionApp3.appServicePlanId(), functionApp1.appServicePlanId()); } private static final String FUNCTION_APP_PACKAGE_URL = "https: @Test public void canCRUDLinuxFunctionApp() throws Exception { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(Region.US_EAST, plan1.region()); Assertions.assertEquals(new PricingTier(SkuName.DYNAMIC.toString(), "Y1"), plan1.pricingTier()); Assertions.assertTrue(plan1.innerModel().reserved()); Assertions .assertTrue( Arrays .asList(functionApp1.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); PagedIterable<FunctionAppBasic> functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(1, TestUtilities.getSize(functionApps)); FunctionApp functionApp2 = appServiceManager .functionApps() .define(webappName2) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName1) .withNewLinuxAppServicePlan(PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp2); assertLinuxJava(functionApp2, FunctionRuntimeStack.JAVA_8); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(functionApp2.appServicePlanId()); Assertions.assertNotNull(plan2); Assertions.assertEquals(PricingTier.STANDARD_S1, plan2.pricingTier()); Assertions.assertTrue(plan2.innerModel().reserved()); FunctionApp functionApp3 = appServiceManager .functionApps() .define(webappName3) .withExistingLinuxAppServicePlan(plan2) .withExistingResourceGroup(rgName1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp3); assertLinuxJava(functionApp3, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } functionApps = appServiceManager.functionApps().listByResourceGroup(rgName1); Assertions.assertEquals(3, TestUtilities.getSize(functionApps)); PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp2.resourceGroupName(), functionApp2.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); functions = appServiceManager.functionApps().listFunctions(functionApp3.resourceGroupName(), functionApp3.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test public void canCRUDLinuxFunctionAppPremium() { rgName2 = null; FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assertions.assertNotNull(plan1); Assertions.assertEquals(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8); if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(3)); } PagedIterable<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assertions.assertEquals(1, TestUtilities.getSize(functions)); } @Test @Disabled("Need container registry") public void canCRUDLinuxFunctionAppPremiumDocker() { FunctionApp functionApp1 = appServiceManager .functionApps() .define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxAppServicePlan(new PricingTier(SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withPrivateRegistryImage( "weidxuregistry.azurecr.io/az-func-java:v1", "https: .withCredentials("weidxuregistry", "PASSWORD") .withRuntime("java") .withRuntimeVersion("~3") .create(); if (!isPlaybackMode()) { functionApp1.zipDeploy(new File(FunctionAppsTests.class.getResource("/java-functions.zip").getPath())); } } @Test public void canCRUDLinuxFunctionAppJava11() throws Exception { rgName2 = null; String runtimeVersion = "~4"; FunctionApp functionApp1 = appServiceManager.functionApps().define(webappName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName1) .withNewLinuxConsumptionPlan() .withBuiltInImage(FunctionRuntimeStack.JAVA_11) .withRuntimeVersion(runtimeVersion) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assertions.assertNotNull(functionApp1); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_11, runtimeVersion); assertRunning(functionApp1); } @Test private void assertRunning(FunctionApp functionApp) { if (!isPlaybackMode()) { ResourceManagerUtils.sleep(Duration.ofMinutes(1)); String name = "linux_function_app"; Response<String> response = curl("https: + "/api/HttpTrigger-Java?name=" + name); Assertions.assertEquals(200, response.getStatusCode()); String body = response.getValue(); Assertions.assertNotNull(body); Assertions.assertTrue(body.contains("Hello, " + name)); } } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack) { return assertLinuxJava(functionApp, stack, null); } private static Map<String, AppSetting> assertLinuxJava(FunctionApp functionApp, FunctionRuntimeStack stack, String runtimeVersion) { Assertions.assertEquals(stack.getLinuxFxVersion(), functionApp.linuxFxVersion()); Assertions .assertTrue( Arrays .asList(functionApp.innerModel().kind().split(Pattern.quote(","))) .containsAll(Arrays.asList("linux", "functionapp"))); Assertions.assertTrue(functionApp.innerModel().reserved()); Map<String, AppSetting> appSettings = functionApp.getAppSettings(); Assertions.assertNotNull(appSettings); Assertions.assertNotNull(appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE)); Assertions.assertEquals( stack.runtime(), appSettings.get(KEY_FUNCTIONS_WORKER_RUNTIME).value()); Assertions.assertEquals( runtimeVersion == null ? stack.version() : runtimeVersion, appSettings.get(KEY_FUNCTIONS_EXTENSION_VERSION).value()); return appSettings; } private static final String KEY_AZURE_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String KEY_CONTENT_AZURE_FILE_CONNECTION_STRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String KEY_CONTENT_SHARE = "WEBSITE_CONTENTSHARE"; private static final String KEY_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String KEY_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; private static final String ACCOUNT_NAME_SEGMENT = "AccountName="; private static final String ACCOUNT_KEY_SEGMENT = "AccountKey="; private static class FunctionAppResource { Map<String, AppSetting> appSettings; String accountName; String accountKey; StorageAccount storageAccount; } private static FunctionAppResource getStorageAccount(StorageManager storageManager, FunctionApp functionApp) { FunctionAppResource resource = new FunctionAppResource(); resource.appSettings = functionApp.getAppSettings(); String storageAccountConnectionString = resource.appSettings.get(KEY_AZURE_WEB_JOBS_STORAGE).value(); String[] segments = storageAccountConnectionString.split(";"); for (String segment : segments) { if (segment.startsWith(ACCOUNT_NAME_SEGMENT)) { resource.accountName = segment.substring(ACCOUNT_NAME_SEGMENT.length()); } else if (segment.startsWith(ACCOUNT_KEY_SEGMENT)) { resource.accountKey = segment.substring(ACCOUNT_KEY_SEGMENT.length()); } } if (resource.accountName != null) { PagedIterable<StorageAccount> storageAccounts = storageManager.storageAccounts().list(); for (StorageAccount storageAccount : storageAccounts) { if (resource.accountName.equals(storageAccount.name())) { resource.storageAccount = storageAccount; break; } } } return resource; } }
The client ID isn't required in all managed identity cases (depends on platform and configuration) and `DefaultAzureCredential` won't always use managed identity (for example, when a dev runs this sample on a local machine). I suggest directing people to `DefaultAzureCredential` docs instead of getting into authentication details here.
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. To make default credentials work, ensure that the environment variable 'AZURE_CLIENT_ID' is set with the principal ID of a managed identity that has been given access to your vault. To get started, you'll need a URL to an Azure Key Vault. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
'AZURE_CLIENT_ID' is set with the principal ID of a managed identity that has been given access to your vault.
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. For more information on this and other types of credentials, see this document: https: To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("<your-managed-hsm-url>") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
Thanks for catching that, I forgot the environment variable is not necessary in Azure-managed resources (VMs, Azure Functions, etc.) As for mentioning the use of a managed identity instead of simply referring to the `DefaultAzureCredential` docs, I was under the impression the effort @jlichwa is leading on updating auth samples required us to direct customers to the use managed identity. If we can get away with not telling people to use something in particular and sending them to `azure-identity` I would prefer that, but I will let Jack chime in here.
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. To make default credentials work, ensure that the environment variable 'AZURE_CLIENT_ID' is set with the principal ID of a managed identity that has been given access to your vault. To get started, you'll need a URL to an Azure Key Vault. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
'AZURE_CLIENT_ID' is set with the principal ID of a managed identity that has been given access to your vault.
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. For more information on this and other types of credentials, see this document: https: To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("<your-managed-hsm-url>") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
I wonder if it's even worth duplicating this documentation, or just link to the DefaultAzureCredential docs. I suppose it doesn't hurt here, but the code sample itself doesn't really change: just use a DefaultAzureCredential. Could use env vars, Azure CLI context, VS creds, etc.
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. To make default credentials work, ensure that the environment variable 'AZURE_CLIENT_ID' is set with the principal ID of a managed identity that has been given access to your vault. To get started, you'll need a URL to an Azure Key Vault. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
using default Azure credentials. To make default credentials work, ensure that the environment variable
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. For more information on this and other types of credentials, see this document: https: To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("<your-managed-hsm-url>") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
I linked to the `DefaultAzureCredential` docs.
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. To make default credentials work, ensure that the environment variable 'AZURE_CLIENT_ID' is set with the principal ID of a managed identity that has been given access to your vault. To get started, you'll need a URL to an Azure Key Vault. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
using default Azure credentials. To make default credentials work, ensure that the environment variable
public static void main(String[] args) { /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is using default Azure credentials. For more information on this and other types of credentials, see this document: https: To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README (https: for links and instructions. */ KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() .vaultUrl("<your-managed-hsm-url>") .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); /* In order to assign a role to a service principal, we'll have to know which role definitions are available. Let's get all of them. */ List<KeyVaultRoleDefinition> roleDefinitions = new ArrayList<>(); for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { roleDefinitions.add(roleDefinition); System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); } for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); } /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleAssignments(). See the README (https: for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command: az ad signed-in-user show --query objectId */ String servicePrincipalId = "<service-principal-id>"; KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); KeyVaultRoleAssignment createdRoleAssignment = accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), servicePrincipalId); System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the createdAssignment from the previous example. */ KeyVaultRoleAssignment retrievedRoleAssignment = accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the createdAssignment from the previous example. */ accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
class AccessControlHelloWorld { /** * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault URL is passed. */ }
do we need to bind again? It's already a `DataSourceProperties` bean.
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = Binder.get(environment).bindOrCreate("spring.datasource", DataSourceProperties.class); boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.debug("'spring.datasource.password' provided, skip JdbcPropertiesBeanPostProcessor."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip JdbcPropertiesBeanPostProcessor."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve connection string from provided {}, skip JdbcPropertiesBeanPostProcessor.", url); return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginEnabled()) { LOGGER.info("The jdbc plugin with provided jdbc schema is not on the classpath , skip JdbcPropertiesBeanPostProcessor"); return bean; } try { AzureCredentialFreeProperties properties = Binder.get(environment).bindOrCreate("spring.datasource.azure", AzureCredentialFreeProperties.class); Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip JdbcPropertiesBeanPostProcessor"); } } return bean; }
DataSourceProperties dataSourceProperties = Binder.get(environment).bindOrCreate("spring.datasource", DataSourceProperties.class);
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = (DataSourceProperties) bean; AzureCredentialFreeProperties properties = Binder.get(environment) .bindOrCreate(SPRING_CLOUD_AZURE_DATASOURCE_PREFIX, AzureCredentialFreeProperties.class); if (!properties.isCredentialFreeEnabled()) { LOGGER.debug("Feature credential free is not enabled, skip enhancing jdbc url."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip enhancing jdbc url."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve jdbc connection string from provided {}, skip enhancing jdbc url.", url); return bean; } boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.debug( "If you are using Azure hosted services," + "it is encouraged to use the credential-free feature. " + "Please refer to https: return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginAvailable()) { LOGGER.debug("The jdbc plugin with provided jdbc schema is not on the classpath, skip enhancing jdbc url."); return bean; } try { Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip enhancing jdbc url."); } } return bean; }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER = "com.azure.spring.cloud.service.implementation.identity.impl.credential.provider.SpringTokenCredentialProvider"; private final AzureGlobalProperties azureGlobalProperties; private Environment environment; public JdbcPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } private static final Map<String, String> POSTGRES_ENHANCED_PROPERTIES = new TreeMap<>(); private static final Map<String, String> MYSQL_ENHANCED_PROPERTIES = new TreeMap<>(); static final Map<DatabaseType, Map<String, String>> DEFAULT_ENHANCED_PROPERTIES = new HashMap<>(); static { POSTGRES_ENHANCED_PROPERTIES.put(PROPERTY_NAME_POSTGRESQL_AUTHENTICATION_PLUGIN_CLASSNAME, POSTGRES_AUTH_PLUGIN_CLASS_NAME); POSTGRES_ENHANCED_PROPERTIES.put(PROPERTY_NAME_POSTGRESQL_SSL_MODE, PROPERTY_VALUE_POSTGRESQL_SSL_MODE); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_SSL_MODE, PROPERTY_VALUE_MYSQL_SSL_MODE); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_USE_SSL, PROPERTY_VALUE_MYSQL_USE_SSL); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_DEFAULT_AUTHENTICATION_PLUGIN, MYSQL_AUTH_PLUGIN_CLASS_NAME); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_AUTHENTICATION_PLUGINS, MYSQL_AUTH_PLUGIN_CLASS_NAME); DEFAULT_ENHANCED_PROPERTIES.put(DatabaseType.MYSQL, MYSQL_ENHANCED_PROPERTIES); DEFAULT_ENHANCED_PROPERTIES.put(DatabaseType.POSTGRESQL, POSTGRES_ENHANCED_PROPERTIES); } @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); TokenCredential globalTokenCredential = new AzureTokenCredentialResolver().resolve(azureGlobalProperties); TokenCredential credentialFreeTokenCredential = new AzureTokenCredentialResolver().resolve(properties); if (globalTokenCredential != null && credentialFreeTokenCredential == null) { LOGGER.info("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.CLIENT_ID.setProperty(result, properties.getCredential().getClientId()); AuthProperty.CLIENT_SECRET.setProperty(result, properties.getCredential().getClientSecret()); AuthProperty.CLIENT_CERTIFICATE_PATH.setProperty(result, properties.getCredential().getClientCertificatePath()); AuthProperty.CLIENT_CERTIFICATE_PASSWORD.setProperty(result, properties.getCredential().getClientCertificatePassword()); AuthProperty.USERNAME.setProperty(result, properties.getCredential().getUsername()); AuthProperty.PASSWORD.setProperty(result, properties.getCredential().getPassword()); AuthProperty.MANAGED_IDENTITY_ENABLED.setProperty(result, String.valueOf(properties.getCredential().isManagedIdentityEnabled())); AuthProperty.AUTHORITY_HOST.setProperty(result, String.valueOf(properties.getProfile().getEnvironment().getActiveDirectoryEndpoint())); AuthProperty.TENANT_ID.setProperty(result, String.valueOf(properties.getProfile().getTenantId())); if (DEFAULT_ENHANCED_PROPERTIES.get(databaseType) != null) { result.putAll(DEFAULT_ENHANCED_PROPERTIES.get(databaseType)); } return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME = SpringTokenCredentialProvider.class.getName(); private static final String SPRING_CLOUD_AZURE_DATASOURCE_PREFIX = "spring.datasource.azure"; private GenericApplicationContext applicationContext; private Environment environment; @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); AzureTokenCredentialResolver resolver = applicationContext.getBean(AzureTokenCredentialResolver.class); TokenCredential tokenCredential = resolver.resolve(properties); if (tokenCredential != null) { LOGGER.debug("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_BEAN_NAME.setProperty(result, CREDENTIAL_FREE_TOKEN_BEAN_NAME); applicationContext.registerBean(CREDENTIAL_FREE_TOKEN_BEAN_NAME, TokenCredential.class, () -> tokenCredential); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME); databaseType.setDefaultEnhancedProperties(result); return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (GenericApplicationContext) applicationContext; } }
No, updated.
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = Binder.get(environment).bindOrCreate("spring.datasource", DataSourceProperties.class); boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.debug("'spring.datasource.password' provided, skip JdbcPropertiesBeanPostProcessor."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip JdbcPropertiesBeanPostProcessor."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve connection string from provided {}, skip JdbcPropertiesBeanPostProcessor.", url); return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginEnabled()) { LOGGER.info("The jdbc plugin with provided jdbc schema is not on the classpath , skip JdbcPropertiesBeanPostProcessor"); return bean; } try { AzureCredentialFreeProperties properties = Binder.get(environment).bindOrCreate("spring.datasource.azure", AzureCredentialFreeProperties.class); Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip JdbcPropertiesBeanPostProcessor"); } } return bean; }
DataSourceProperties dataSourceProperties = Binder.get(environment).bindOrCreate("spring.datasource", DataSourceProperties.class);
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = (DataSourceProperties) bean; AzureCredentialFreeProperties properties = Binder.get(environment) .bindOrCreate(SPRING_CLOUD_AZURE_DATASOURCE_PREFIX, AzureCredentialFreeProperties.class); if (!properties.isCredentialFreeEnabled()) { LOGGER.debug("Feature credential free is not enabled, skip enhancing jdbc url."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip enhancing jdbc url."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve jdbc connection string from provided {}, skip enhancing jdbc url.", url); return bean; } boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.debug( "If you are using Azure hosted services," + "it is encouraged to use the credential-free feature. " + "Please refer to https: return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginAvailable()) { LOGGER.debug("The jdbc plugin with provided jdbc schema is not on the classpath, skip enhancing jdbc url."); return bean; } try { Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip enhancing jdbc url."); } } return bean; }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER = "com.azure.spring.cloud.service.implementation.identity.impl.credential.provider.SpringTokenCredentialProvider"; private final AzureGlobalProperties azureGlobalProperties; private Environment environment; public JdbcPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } private static final Map<String, String> POSTGRES_ENHANCED_PROPERTIES = new TreeMap<>(); private static final Map<String, String> MYSQL_ENHANCED_PROPERTIES = new TreeMap<>(); static final Map<DatabaseType, Map<String, String>> DEFAULT_ENHANCED_PROPERTIES = new HashMap<>(); static { POSTGRES_ENHANCED_PROPERTIES.put(PROPERTY_NAME_POSTGRESQL_AUTHENTICATION_PLUGIN_CLASSNAME, POSTGRES_AUTH_PLUGIN_CLASS_NAME); POSTGRES_ENHANCED_PROPERTIES.put(PROPERTY_NAME_POSTGRESQL_SSL_MODE, PROPERTY_VALUE_POSTGRESQL_SSL_MODE); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_SSL_MODE, PROPERTY_VALUE_MYSQL_SSL_MODE); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_USE_SSL, PROPERTY_VALUE_MYSQL_USE_SSL); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_DEFAULT_AUTHENTICATION_PLUGIN, MYSQL_AUTH_PLUGIN_CLASS_NAME); MYSQL_ENHANCED_PROPERTIES.put(PROPERTY_NAME_MYSQL_AUTHENTICATION_PLUGINS, MYSQL_AUTH_PLUGIN_CLASS_NAME); DEFAULT_ENHANCED_PROPERTIES.put(DatabaseType.MYSQL, MYSQL_ENHANCED_PROPERTIES); DEFAULT_ENHANCED_PROPERTIES.put(DatabaseType.POSTGRESQL, POSTGRES_ENHANCED_PROPERTIES); } @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); TokenCredential globalTokenCredential = new AzureTokenCredentialResolver().resolve(azureGlobalProperties); TokenCredential credentialFreeTokenCredential = new AzureTokenCredentialResolver().resolve(properties); if (globalTokenCredential != null && credentialFreeTokenCredential == null) { LOGGER.info("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.CLIENT_ID.setProperty(result, properties.getCredential().getClientId()); AuthProperty.CLIENT_SECRET.setProperty(result, properties.getCredential().getClientSecret()); AuthProperty.CLIENT_CERTIFICATE_PATH.setProperty(result, properties.getCredential().getClientCertificatePath()); AuthProperty.CLIENT_CERTIFICATE_PASSWORD.setProperty(result, properties.getCredential().getClientCertificatePassword()); AuthProperty.USERNAME.setProperty(result, properties.getCredential().getUsername()); AuthProperty.PASSWORD.setProperty(result, properties.getCredential().getPassword()); AuthProperty.MANAGED_IDENTITY_ENABLED.setProperty(result, String.valueOf(properties.getCredential().isManagedIdentityEnabled())); AuthProperty.AUTHORITY_HOST.setProperty(result, String.valueOf(properties.getProfile().getEnvironment().getActiveDirectoryEndpoint())); AuthProperty.TENANT_ID.setProperty(result, String.valueOf(properties.getProfile().getTenantId())); if (DEFAULT_ENHANCED_PROPERTIES.get(databaseType) != null) { result.putAll(DEFAULT_ENHANCED_PROPERTIES.get(databaseType)); } return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME = SpringTokenCredentialProvider.class.getName(); private static final String SPRING_CLOUD_AZURE_DATASOURCE_PREFIX = "spring.datasource.azure"; private GenericApplicationContext applicationContext; private Environment environment; @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); AzureTokenCredentialResolver resolver = applicationContext.getBean(AzureTokenCredentialResolver.class); TokenCredential tokenCredential = resolver.resolve(properties); if (tokenCredential != null) { LOGGER.debug("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_BEAN_NAME.setProperty(result, CREDENTIAL_FREE_TOKEN_BEAN_NAME); applicationContext.registerBean(CREDENTIAL_FREE_TOKEN_BEAN_NAME, TokenCredential.class, () -> tokenCredential); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME); databaseType.setDefaultEnhancedProperties(result); return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (GenericApplicationContext) applicationContext; } }
this logic is wired. why if the object doesn't `hasProperties` then use `QueryDelimiter` or `PathQueryDelimiter`
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
if (!this.hasProperties()) {
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance jdbc url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("port", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("servername", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
what happen if the jdbcURL user provided already have some property defined but with different value? for example, in the URL, it already have `PROPERTY_NAME_MYSQL_SSL_MODE` with a different than `PROPERTY_VALUE_MYSQL_SSL_MODE` value?
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) {
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance jdbc url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("port", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("servername", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
when this log will be priented out?
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = (DataSourceProperties) bean; AzureCredentialFreeProperties properties = Binder.get(environment) .bindOrCreate(SPRING_CLOUD_AZURE_DATASOURCE_PREFIX, AzureCredentialFreeProperties.class); if (!properties.isCredentialFreeEnabled()) { LOGGER.debug("Feature credential free is not enabled, skip enhancing jdbc url."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip enhancing jdbc url."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve jdbc connection string from provided {}, skip enhancing jdbc url.", url); return bean; } boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.info("Value of 'spring.datasource.password' is detected, if you are using Azure hosted services," + "it is encouraged to use the credential-free feature. " + "Please refer to https: return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginAvailable()) { LOGGER.debug("The jdbc plugin with provided jdbc schema is not on the classpath, skip enhancing jdbc url."); return bean; } try { Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip enhancing jdbc url."); } } return bean; }
LOGGER.info("Value of 'spring.datasource.password' is detected, if you are using Azure hosted services,"
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = (DataSourceProperties) bean; AzureCredentialFreeProperties properties = Binder.get(environment) .bindOrCreate(SPRING_CLOUD_AZURE_DATASOURCE_PREFIX, AzureCredentialFreeProperties.class); if (!properties.isCredentialFreeEnabled()) { LOGGER.debug("Feature credential free is not enabled, skip enhancing jdbc url."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip enhancing jdbc url."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve jdbc connection string from provided {}, skip enhancing jdbc url.", url); return bean; } boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.debug( "If you are using Azure hosted services," + "it is encouraged to use the credential-free feature. " + "Please refer to https: return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginAvailable()) { LOGGER.debug("The jdbc plugin with provided jdbc schema is not on the classpath, skip enhancing jdbc url."); return bean; } try { Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip enhancing jdbc url."); } } return bean; }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME = SpringTokenCredentialProvider.class.getName(); private static final String SPRING_CLOUD_AZURE_DATASOURCE_PREFIX = "spring.datasource.azure"; private GenericApplicationContext applicationContext; private Environment environment; @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); TokenCredential credentialFreeTokenCredential = new AzureTokenCredentialResolver().resolve(properties); if (credentialFreeTokenCredential != null) { LOGGER.debug("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_BEAN_NAME.setProperty(result, CREDENTIAL_FREE_TOKEN_BEAN_NAME); applicationContext.registerBean(CREDENTIAL_FREE_TOKEN_BEAN_NAME, TokenCredential.class, () -> credentialFreeTokenCredential); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME); AuthProperty.AUTHORITY_HOST.setProperty(result, properties.getProfile().getEnvironment().getActiveDirectoryEndpoint()); AuthProperty.TENANT_ID.setProperty(result, properties.getProfile().getTenantId()); databaseType.setDefaultEnhancedProperties(result); return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (GenericApplicationContext) applicationContext; } }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME = SpringTokenCredentialProvider.class.getName(); private static final String SPRING_CLOUD_AZURE_DATASOURCE_PREFIX = "spring.datasource.azure"; private GenericApplicationContext applicationContext; private Environment environment; @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); AzureTokenCredentialResolver resolver = applicationContext.getBean(AzureTokenCredentialResolver.class); TokenCredential tokenCredential = resolver.resolve(properties); if (tokenCredential != null) { LOGGER.debug("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_BEAN_NAME.setProperty(result, CREDENTIAL_FREE_TOKEN_BEAN_NAME); applicationContext.registerBean(CREDENTIAL_FREE_TOKEN_BEAN_NAME, TokenCredential.class, () -> tokenCredential); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME); databaseType.setDefaultEnhancedProperties(result); return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (GenericApplicationContext) applicationContext; } }
Yes, it's a little wired here, `QueryDelimiter` may be different from `PathQueryDelimiter`, - If jdbcurl has no properties like ` jdbc:postgresql://postgre:5432/test`, before adding enhanced properties, we need to append a `?` at the end. - If the jdbcurl has properties like ` jdbc:postgresql://postgre:5432/test?azure.clientId=1234`, we need to append a `&` at the end. Here are some jdbcurl examples. ``` jdbc:postgresql://postgre:5432/test?azure.clientId=1234 jdbc:postgresql://postgre:5432/test?azure.clientId=1234&azure.clientSecret=**** jdbc:postgresql://postgre:5432/test ```
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
if (!this.hasProperties()) {
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance jdbc url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("port", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("servername", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
It will throw IllegalArgumentException("Inconsistent property detected").
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) {
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance jdbc url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("port", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("servername", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
so make the code more readable
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
if (!this.hasProperties()) {
public String enhanceConnectionString(Map<String, String> enhancedProperties) { if (enhancedProperties == null || enhancedProperties.isEmpty()) { return this.jdbcURL; } LOGGER.debug("Trying to enhance jdbc url for {}", databaseType); StringBuilder builder = new StringBuilder(this.jdbcURL); if (!this.hasProperties()) { builder.append(databaseType.getPathQueryDelimiter()); } else { builder.append(databaseType.getQueryDelimiter()); } for (Map.Entry<String, String> entry : enhancedProperties.entrySet()) { String key = entry.getKey(), value = entry.getValue(); String valueProvidedInConnectionString = this.getProperty(key); if (valueProvidedInConnectionString == null) { builder.append(key) .append("=") .append(value) .append(databaseType.getQueryDelimiter()); } else if (!value.equals(valueProvidedInConnectionString)) { LOGGER.debug("The property {} is set to another value than default {}", key, value); throw new IllegalArgumentException("Inconsistent property detected"); } else { LOGGER.debug("The property {} is already set", key); } } String enhancedUrl = builder.toString(); return enhancedUrl.substring(0, enhancedUrl.length() - 1); }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("port", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
class JdbcConnectionString { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcConnectionString.class); public static final String INVALID_CONNECTION_STRING_FORMAT = "Invalid connection string: %s"; public static final String UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT = "The DatabaseType specified in : %s is not " + "supported to enhance authentication with Azure AD by Spring Cloud Azure."; public static final String INVALID_PROPERTY_PAIR_FORMAT = "Connection string has invalid key value pair: %s"; private static final String TOKEN_VALUE_SEPARATOR = "="; private final String jdbcURL; private final Map<String, String> properties = new HashMap<>(); private DatabaseType databaseType = null; private JdbcConnectionString(String jdbcURL) { this.jdbcURL = jdbcURL; } private void resolveSegments() { if (!StringUtils.hasText(this.jdbcURL)) { LOGGER.warn("'connectionString' doesn't have text."); throw new IllegalArgumentException(String.format(INVALID_CONNECTION_STRING_FORMAT, this.jdbcURL)); } Optional<DatabaseType> optionalDatabaseType = Arrays.stream(DatabaseType.values()) .filter(databaseType -> this.jdbcURL.startsWith(databaseType.getSchema())) .findAny(); this.databaseType = optionalDatabaseType.orElseThrow(() -> new AzureUnsupportedDatabaseTypeException(String.format(UNSUPPORTED_DATABASE_TYPE_STRING_FORMAT, this.jdbcURL))); int pathQueryDelimiterIndex = this.jdbcURL.indexOf(this.databaseType.getPathQueryDelimiter()); if (pathQueryDelimiterIndex < 0) { return; } String hostInfo = this.jdbcURL.substring(databaseType.getSchema().length() + 3, pathQueryDelimiterIndex); String[] hostInfoArray = hostInfo.split(":"); if (hostInfoArray.length == 2) { this.properties.put("servername", hostInfoArray[0]); this.properties.put("port", hostInfoArray[1]); } else { this.properties.put("servername", hostInfo); } String properties = this.jdbcURL.substring(pathQueryDelimiterIndex + 1); final String[] tokenValuePairs = properties.split(this.databaseType.getQueryDelimiter()); for (String tokenValuePair : tokenValuePairs) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); String key = pair[0]; if (!StringUtils.hasText(pair[0])) { throw new IllegalArgumentException(String.format(INVALID_PROPERTY_PAIR_FORMAT, tokenValuePair)); } if (pair.length < 2) { this.properties.put(key, NONE_VALUE); } else { this.properties.put(key, pair[1]); } } } public String getProperty(String key) { return this.properties.get(key); } public DatabaseType getDatabaseType() { return databaseType; } public boolean hasProperties() { return !this.properties.isEmpty(); } public static JdbcConnectionString resolve(String url) { JdbcConnectionString jdbcConnectionString = new JdbcConnectionString(url); try { jdbcConnectionString.resolveSegments(); } catch (AzureUnsupportedDatabaseTypeException e) { LOGGER.debug(e.getMessage()); return null; } return jdbcConnectionString; } }
it should be logged and only when the application can use credential-free but not
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = (DataSourceProperties) bean; AzureCredentialFreeProperties properties = Binder.get(environment) .bindOrCreate(SPRING_CLOUD_AZURE_DATASOURCE_PREFIX, AzureCredentialFreeProperties.class); if (!properties.isCredentialFreeEnabled()) { LOGGER.debug("Feature credential free is not enabled, skip enhancing jdbc url."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip enhancing jdbc url."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve jdbc connection string from provided {}, skip enhancing jdbc url.", url); return bean; } boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.info("Value of 'spring.datasource.password' is detected, if you are using Azure hosted services," + "it is encouraged to use the credential-free feature. " + "Please refer to https: return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginAvailable()) { LOGGER.debug("The jdbc plugin with provided jdbc schema is not on the classpath, skip enhancing jdbc url."); return bean; } try { Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip enhancing jdbc url."); } } return bean; }
LOGGER.info("Value of 'spring.datasource.password' is detected, if you are using Azure hosted services,"
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSourceProperties) { DataSourceProperties dataSourceProperties = (DataSourceProperties) bean; AzureCredentialFreeProperties properties = Binder.get(environment) .bindOrCreate(SPRING_CLOUD_AZURE_DATASOURCE_PREFIX, AzureCredentialFreeProperties.class); if (!properties.isCredentialFreeEnabled()) { LOGGER.debug("Feature credential free is not enabled, skip enhancing jdbc url."); return bean; } String url = dataSourceProperties.getUrl(); if (!StringUtils.hasText(url)) { LOGGER.debug("No 'spring.datasource.url' provided, skip enhancing jdbc url."); return bean; } JdbcConnectionString connectionString = JdbcConnectionString.resolve(url); if (connectionString == null) { LOGGER.debug("Can not resolve jdbc connection string from provided {}, skip enhancing jdbc url.", url); return bean; } boolean isPasswordProvided = StringUtils.hasText(dataSourceProperties.getPassword()); if (isPasswordProvided) { LOGGER.debug( "If you are using Azure hosted services," + "it is encouraged to use the credential-free feature. " + "Please refer to https: return bean; } DatabaseType databaseType = connectionString.getDatabaseType(); if (!databaseType.isDatabasePluginAvailable()) { LOGGER.debug("The jdbc plugin with provided jdbc schema is not on the classpath, skip enhancing jdbc url."); return bean; } try { Map<String, String> enhancedProperties = buildEnhancedProperties(databaseType, properties); String enhancedUrl = connectionString.enhanceConnectionString(enhancedProperties); ((DataSourceProperties) bean).setUrl(enhancedUrl); } catch (IllegalArgumentException e) { LOGGER.debug("Inconsistent properties detected, skip enhancing jdbc url."); } } return bean; }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME = SpringTokenCredentialProvider.class.getName(); private static final String SPRING_CLOUD_AZURE_DATASOURCE_PREFIX = "spring.datasource.azure"; private GenericApplicationContext applicationContext; private Environment environment; @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); TokenCredential credentialFreeTokenCredential = new AzureTokenCredentialResolver().resolve(properties); if (credentialFreeTokenCredential != null) { LOGGER.debug("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_BEAN_NAME.setProperty(result, CREDENTIAL_FREE_TOKEN_BEAN_NAME); applicationContext.registerBean(CREDENTIAL_FREE_TOKEN_BEAN_NAME, TokenCredential.class, () -> credentialFreeTokenCredential); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME); AuthProperty.AUTHORITY_HOST.setProperty(result, properties.getProfile().getEnvironment().getActiveDirectoryEndpoint()); AuthProperty.TENANT_ID.setProperty(result, properties.getProfile().getTenantId()); databaseType.setDefaultEnhancedProperties(result); return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (GenericApplicationContext) applicationContext; } }
class JdbcPropertiesBeanPostProcessor implements BeanPostProcessor, EnvironmentAware, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPropertiesBeanPostProcessor.class); private static final String SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME = SpringTokenCredentialProvider.class.getName(); private static final String SPRING_CLOUD_AZURE_DATASOURCE_PREFIX = "spring.datasource.azure"; private GenericApplicationContext applicationContext; private Environment environment; @Override private Map<String, String> buildEnhancedProperties(DatabaseType databaseType, AzureCredentialFreeProperties properties) { Map<String, String> result = new HashMap<>(); AzureTokenCredentialResolver resolver = applicationContext.getBean(AzureTokenCredentialResolver.class); TokenCredential tokenCredential = resolver.resolve(properties); if (tokenCredential != null) { LOGGER.debug("Add SpringTokenCredentialProvider as the default token credential provider."); AuthProperty.TOKEN_CREDENTIAL_BEAN_NAME.setProperty(result, CREDENTIAL_FREE_TOKEN_BEAN_NAME); applicationContext.registerBean(CREDENTIAL_FREE_TOKEN_BEAN_NAME, TokenCredential.class, () -> tokenCredential); } AuthProperty.CACHE_ENABLED.setProperty(result, "true"); AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.setProperty(result, SPRING_TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME); databaseType.setDefaultEnhancedProperties(result); return result; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (GenericApplicationContext) applicationContext; } }
nit: why not assert both is the same request?
public void simpleDownloadTest(Context context) { StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> response.getValue().map(ByteBuffer::remaining).reduce(0, Integer::sum), StreamResponse::close)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))), StreamResponse::close)) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); }
StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context),
public void simpleDownloadTest(Context context) { StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> response.getValue().map(ByteBuffer::remaining).reduce(0, Integer::sum), StreamResponse::close)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))), StreamResponse::close)) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); }
class RestProxyTests { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; /** * Get the HTTP client that will be used for each test. This will be called once per test. * * @return The HTTP client to use for each test. */ protected abstract HttpClient createHttpClient(); /** * Get the dynamic port the WireMock server is using to properly route the request. * * @return The HTTP port WireMock is using. */ protected abstract int getWireMockPort(); @Host("http: @ServiceInterface(name = "Service1") private interface Service1 { @Get("bytes/100") @ExpectedResponses({200}) byte[] getByteArray(); @Get("bytes/100") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(); @Get("bytes/100") Mono<byte[]> getByteArrayAsyncWithNoExpectedResponses(); } @Test public void syncRequestWithByteArrayReturnType() { final byte[] result = createService(Service1.class).getByteArray(); assertNotNull(result); assertEquals(100, result.length); } @Test public void asyncRequestWithByteArrayReturnType() { StepVerifier.create(createService(Service1.class).getByteArrayAsync()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void getByteArrayAsyncWithNoExpectedResponses() { StepVerifier.create(createService(Service1.class).getByteArrayAsyncWithNoExpectedResponses()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service2") private interface Service2 { @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) byte[] getByteArray(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); } @Test public void syncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 100); assertNotNull(result); assertEquals(result.length, 100); } @Test public void asyncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { StepVerifier.create(createService(Service2.class).getByteArrayAsync("localhost", 100)) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void syncRequestWithEmptyByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 0); assertNull(result); } @Host("http: @ServiceInterface(name = "Service3") private interface Service3 { @Get("bytes/100") @ExpectedResponses({200}) void getNothing(); @Get("bytes/100") @ExpectedResponses({200}) Mono<Void> getNothingAsync(); } @Test public void syncGetRequestWithNoReturn() { assertDoesNotThrow(() -> createService(Service3.class).getNothing()); } @Test public void asyncGetRequestWithNoReturn() { StepVerifier.create(createService(Service3.class).getNothingAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service5") private interface Service5 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(); @Get("anything/with+plus") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPlus(); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPathParam(@PathParam("path") String pathParam); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncodedPathParam(@PathParam(value = "path", encoded = true) String pathParam); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(); } @Test public void syncGetRequestWithAnything() { final HttpBinJSON json = createService(Service5.class).getAnything(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); } @Test public void syncGetRequestWithAnythingWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPlus(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+plus", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithSpace() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with path param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPercent20() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with%20path%20param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void asyncGetRequestWithAnything() { StepVerifier.create(createService(Service5.class).getAnythingAsync()) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service6") private interface Service6 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@QueryParam("a") String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncoded(@QueryParam(value = "a", encoded = true) String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@QueryParam("a") String a, @QueryParam("b") int b); } @Test public void syncGetRequestWithQueryParametersAndAnything() { final HttpBinJSON json = createService(Service6.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnything("A%20Z", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A%2520Z&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithEncodedWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnythingWithEncoded("x%20y", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=x y&b=15", json.url()); } @Test public void asyncGetRequestWithQueryParametersAndAnything() { StepVerifier.create(createService(Service6.class).getAnythingAsync("A", 15)) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url())) .verifyComplete(); } @Test public void syncGetRequestWithNullQueryParameter() { final HttpBinJSON json = createService(Service6.class).getAnything(null, 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?b=15", json.url()); } @Host("http: @ServiceInterface(name = "Service7") private interface Service7 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@HeaderParam("a") String a, @HeaderParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@HeaderParam("a") String a, @HeaderParam("b") int b); } @Test public void syncGetRequestWithHeaderParametersAndAnythingReturn() { final HttpBinJSON json = createService(Service7.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Test public void asyncGetRequestWithHeaderParametersAndAnything() { StepVerifier.create(createService(Service7.class).getAnythingAsync("A", 15)) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); }) .verifyComplete(); } @Test public void syncGetRequestWithNullHeader() { final HttpBinJSON json = createService(Service7.class).getAnything(null, 15); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertNull(headers.getValue("A")); assertArrayEquals(null, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Host("http: @ServiceInterface(name = "Service8") private interface Service8 { @Post("post") @ExpectedResponses({200}) HttpBinJSON post(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); @Post("post") @ExpectedResponses({200}) Mono<HttpBinJSON> postAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); } @Test public void syncPostRequestWithStringBody() { final HttpBinJSON json = createService(Service8.class).post("I'm a post body!"); assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); } @Test public void asyncPostRequestWithStringBody() { StepVerifier.create(createService(Service8.class).postAsync("I'm a post body!")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); }) .verifyComplete(); } @Test public void syncPostRequestWithNullBody() { final HttpBinJSON result = createService(Service8.class).post(null); assertEquals("", result.data()); } @Host("http: @ServiceInterface(name = "Service9") private interface Service9 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) Flux<ByteBuffer> body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) BinaryData body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({201}) HttpBinJSON putWithUnexpectedResponse(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) Mono<HttpBinJSON> putWithUnexpectedResponseAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) HttpBinJSON putWithUnexpectedResponseAndDeterminedExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndDeterminedExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndNoFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); } @Test public void syncPutRequestWithIntBody() { final HttpBinJSON json = createService(Service9.class).put(42); assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); } @Test public void asyncPutRequestWithIntBody() { StepVerifier.create(createService(Service9.class).putAsync(42)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); }).verifyComplete(); } @Test public void syncPutRequestWithBodyAndEqualContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); final HttpBinJSON json = createService(Service9.class).putBodyAndContentLength(body, 4L); assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); } @Test public void syncPutRequestWithBodyLessThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 5L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("less than")); } @Test public void syncPutRequestWithBodyMoreThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 3L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("more than")); } @Test public void asyncPutRequestWithBodyAndEqualContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 4L)) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBodyAndLessThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 5L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBodyAndMoreThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 3L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndEqualContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 4L))) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void syncPutRequestWithUnexpectedResponse() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponse("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponse() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException); HttpResponseException exception = (HttpResponseException) throwable; assertNotNull(exception.getValue()); assertTrue(exception.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) exception.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Test public void syncPutRequestWithUnexpectedResponseAndExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException myRestException = (MyRestException) throwable; assertNotNull(myRestException.getValue()); assertEquals("I'm the body!", myRestException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); HttpResponseException responseException = (HttpResponseException) throwable; assertNotNull(responseException.getValue()); assertTrue(responseException.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) responseException.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Host("http: @ServiceInterface(name = "Service10") private interface Service10 { @Head("anything") @ExpectedResponses({200}) Response<Void> head(); @Head("anything") @ExpectedResponses({200}) boolean headBoolean(); @Head("anything") @ExpectedResponses({200}) void voidHead(); @Head("anything") @ExpectedResponses({200}) Mono<Response<Void>> headAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Boolean> headBooleanAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Void> completableHeadAsync(); } @Test public void syncHeadRequest() { final Void body = createService(Service10.class).head().getValue(); assertNull(body); } @Test public void syncHeadBooleanRequest() { final boolean result = createService(Service10.class).headBoolean(); assertTrue(result); } @Test public void syncVoidHeadRequest() { createService(Service10.class) .voidHead(); } @Test public void asyncHeadRequest() { StepVerifier.create(createService(Service10.class).headAsync()) .assertNext(response -> assertNull(response.getValue())) .verifyComplete(); } @Test public void asyncHeadBooleanRequest() { StepVerifier.create(createService(Service10.class).headBooleanAsync()) .assertNext(Assertions::assertTrue) .verifyComplete(); } @Test public void asyncCompletableHeadRequest() { StepVerifier.create(createService(Service10.class).completableHeadAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service11") private interface Service11 { @Delete("delete") @ExpectedResponses({200}) HttpBinJSON delete(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); @Delete("delete") @ExpectedResponses({200}) Mono<HttpBinJSON> deleteAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); } @Test public void syncDeleteRequest() { final HttpBinJSON json = createService(Service11.class).delete(false); assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); } @Test public void asyncDeleteRequest() { StepVerifier.create(createService(Service11.class).deleteAsync(false)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service12") private interface Service12 { @Patch("patch") @ExpectedResponses({200}) HttpBinJSON patch(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); @Patch("patch") @ExpectedResponses({200}) Mono<HttpBinJSON> patchAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); } @Test public void syncPatchRequest() { final HttpBinJSON json = createService(Service12.class).patch("body-contents"); assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); } @Test public void asyncPatchRequest() { StepVerifier.create(createService(Service12.class).patchAsync("body-contents")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service13") private interface Service13 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) Mono<HttpBinJSON> getAsync(); } @Test public void syncHeadersRequest() { final HttpBinJSON json = createService(Service13.class).get(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); assertEquals("My,Header,Value", headers.getValue("MyOtherHeader")); assertArrayEquals(new String[]{"My", "Header", "Value"}, headers.getValues("MyOtherHeader")); } @Test public void asyncHeadersRequest() { StepVerifier.create(createService(Service13.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service14") private interface Service14 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) Mono<HttpBinJSON> getAsync(); } @Test public void asyncHttpsHeadersRequest() { StepVerifier.create(createService(Service14.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service16") private interface Service16 { @Put("put") @ExpectedResponses({200}) HttpBinJSON putByteArray(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putByteArrayAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); } @Test public void service16Put() { final Service16 service16 = createService(Service16.class); final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; final HttpBinJSON httpBinJSON = service16.putByteArray(expectedBytes); assertTrue(httpBinJSON.data() instanceof String); final String base64String = (String) httpBinJSON.data(); final byte[] actualBytes = base64String.getBytes(); assertArrayEquals(expectedBytes, actualBytes); } @Test public void service16PutAsync() { final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; StepVerifier.create(createService(Service16.class).putByteArrayAsync(expectedBytes)) .assertNext(json -> { assertTrue(json.data() instanceof String); assertArrayEquals(expectedBytes, ((String) json.data()).getBytes()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service17") private interface Service17 { @Get("get") @ExpectedResponses({200}) HttpBinJSON get(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); @Get("get") @ExpectedResponses({200}) Mono<HttpBinJSON> getAsync(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); } @Test public void syncRequestWithMultipleHostParams() { final HttpBinJSON result = createService(Service17.class).get("local", "host"); assertNotNull(result); assertMatchWithHttpOrHttps("localhost/get", result.url()); } @Test public void asyncRequestWithMultipleHostParams() { StepVerifier.create(createService(Service17.class).getAsync("local", "host")) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/get", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service18") private interface Service18 { @Get("status/200") void getStatus200(); @Get("status/200") @ExpectedResponses({200}) void getStatus200WithExpectedResponse200(); @Get("status/300") void getStatus300(); @Get("status/300") @ExpectedResponses({300}) void getStatus300WithExpectedResponse300(); @Get("status/400") void getStatus400(); @Get("status/400") @ExpectedResponses({400}) void getStatus400WithExpectedResponse400(); @Get("status/500") void getStatus500(); @Get("status/500") @ExpectedResponses({500}) void getStatus500WithExpectedResponse500(); } @Test public void service18GetStatus200() { createService(Service18.class).getStatus200(); } @Test public void service18GetStatus200WithExpectedResponse200() { assertDoesNotThrow(() -> createService(Service18.class).getStatus200WithExpectedResponse200()); } @Test public void service18GetStatus300() { createService(Service18.class).getStatus300(); } @Test public void service18GetStatus300WithExpectedResponse300() { assertDoesNotThrow(() -> createService(Service18.class).getStatus300WithExpectedResponse300()); } @Test public void service18GetStatus400() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus400()); } @Test public void service18GetStatus400WithExpectedResponse400() { assertDoesNotThrow(() -> createService(Service18.class).getStatus400WithExpectedResponse400()); } @Test public void service18GetStatus500() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus500()); } @Test public void service18GetStatus500WithExpectedResponse500() { assertDoesNotThrow(() -> createService(Service18.class).getStatus500WithExpectedResponse500()); } @Host("http: @ServiceInterface(name = "Service19") private interface Service19 { @Put("put") HttpBinJSON putWithNoContentTypeAndStringBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithNoContentTypeAndByteArrayBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithHeaderApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") @Headers({"Content-Type: application/json"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") @Headers({"Content-Type: application/json; charset=utf-8"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_JSON + "; charset=utf-8") String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody("hello"); assertEquals("hello", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithNoContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("soups and stuff", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Host("http: @ServiceInterface(name = "Service20") private interface Service20 { @Get("bytes/100") ResponseBase<HttpBinHeaders, Void> getBytes100OnlyHeaders(); @Get("bytes/100") ResponseBase<HttpHeaders, Void> getBytes100OnlyRawHeaders(); @Get("bytes/100") ResponseBase<HttpBinHeaders, byte[]> getBytes100BodyAndHeaders(); @Put("put") ResponseBase<HttpBinHeaders, Void> putOnlyHeaders(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") ResponseBase<HttpBinHeaders, HttpBinJSON> putBodyAndHeaders( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Get("bytes/100") ResponseBase<Void, Void> getBytesOnlyStatus(); @Get("bytes/100") Response<Void> getVoidResponse(); @Put("put") Response<HttpBinJSON> putBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); } @Test public void service20GetBytes100OnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).getBytes100OnlyHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytes100BodyAndHeaders() { final ResponseBase<HttpBinHeaders, byte[]> response = createService(Service20.class).getBytes100BodyAndHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final byte[] body = response.getValue(); assertNotNull(body); assertEquals(100, body.length); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytesOnlyStatus() { final Response<Void> response = createService(Service20.class).getBytesOnlyStatus(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetBytesOnlyHeaders() { final Response<Void> response = createService(Service20.class).getBytes100OnlyRawHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertNotNull(response.getHeaders()); assertNotEquals(0, response.getHeaders().getSize()); } @Test public void service20PutOnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).putOnlyHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20PutBodyAndHeaders() { final ResponseBase<HttpBinHeaders, HttpBinJSON> response = createService(Service20.class).putBodyAndHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetVoidResponse() { final Response<Void> response = createService(Service20.class).getVoidResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetResponseBody() { final Response<HttpBinJSON> response = createService(Service20.class).putBody("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpHeaders headers = response.getHeaders(); assertNotNull(headers); } @Host("http: @ServiceInterface(name = "UnexpectedOKService") interface UnexpectedOKService { @Get("/bytes/1024") @ExpectedResponses({400}) StreamResponse getBytes(); } @Test public void unexpectedHTTPOK() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(UnexpectedOKService.class).getBytes()); assertEquals("Status code 200, (1024-byte body)", e.getMessage()); } @Host("https: @ServiceInterface(name = "Service21") private interface Service21 { @Get("http: @ExpectedResponses({200}) byte[] getBytes100(); } @Test public void service21GetBytes100() { final byte[] bytes = createService(Service21.class).getBytes100(); assertNotNull(bytes); assertEquals(100, bytes.length); } @Host("http: @ServiceInterface(name = "DownloadService") interface DownloadService { @Get("/bytes/30720") StreamResponse getBytes(Context context); @Get("/bytes/30720") Mono<StreamResponse> getBytesAsync(Context context); @Get("/bytes/30720") Flux<ByteBuffer> getBytesFlux(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void simpleDownloadTestAsync(Context context) { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> response.getValue().map(ByteBuffer::remaining) .reduce(0, Integer::sum) .doFinally(ignore -> response.close()))) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))) .doFinally(ignore -> response.close()))) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBody(Context context) throws IOException { try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); streamResponse.transferValueTo(Channels.newChannel(bos)); assertEquals(streamResponse.getHeaders().getValue("ETag"), MessageDigestUtils.md5(bos.toByteArray())); } Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { StepVerifier.create(Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).then(Mono.fromCallable(() -> MessageDigestUtils.md5(Files.readAllBytes(tempFile))))) .assertNext(hash -> assertEquals(streamResponse.getHeaders().getValue("ETag"), hash)) .verifyComplete(); } } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBodyAsync(Context context) throws IOException { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .publishOn(Schedulers.boundedElastic()) .map(streamResponse -> { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { streamResponse.transferValueTo(Channels.newChannel(bos)); } catch (IOException e) { throw Exceptions.propagate(e); } finally { streamResponse.close(); } return Tuples.of(streamResponse.getHeaders().getValue("Etag"), MessageDigestUtils.md5(bos.toByteArray())); })) .assertNext(hashTuple -> assertEquals(hashTuple.getT1(), hashTuple.getT2())) .verifyComplete(); Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(streamResponse -> Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).doFinally(ignored -> streamResponse.close()) .then(Mono.just(streamResponse.getHeaders().getValue("ETag"))))) .assertNext(hash -> { try { assertEquals(hash, MessageDigestUtils.md5(Files.readAllBytes(tempFile))); } catch (IOException e) { Exceptions.propagate(e); } }) .verifyComplete(); } public static Stream<Arguments> downloadTestArgumentProvider() { return Stream.of( Arguments.of(Named.named("default", Context.NONE)), Arguments.of(Named.named("sync proxy enabled", Context.NONE .addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true)))); } @Test public void rawFluxDownloadTest() { StepVerifier.create(createService(DownloadService.class).getBytesFlux() .map(ByteBuffer::remaining).reduce(0, Integer::sum)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface FluxUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") Flux<ByteBuffer> content, @HeaderParam("Content-Length") long contentLength); } @Test public void fluxUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); Flux<ByteBuffer> stream = FluxUtil.readFile(AsynchronousFileChannel.open(filePath)); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(FluxUploadService.class, httpPipeline).put(stream, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Test public void segmentUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(filePath, StandardOpenOption.READ); Response<HttpBinJSON> response = createService(FluxUploadService.class) .put(FluxUtil.readFile(fileChannel, 4, 15), 15); assertEquals("quick brown fox", response.getValue().data()); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface BinaryDataUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") BinaryData content, @HeaderParam("Content-Length") long contentLength); } @Test public void binaryDataUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); BinaryData data = BinaryData.fromFile(filePath); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(BinaryDataUploadService.class, httpPipeline).put(data, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Host("{url}") @ServiceInterface(name = "Service22") interface Service22 { @Get("/") byte[] getBytes(@HostParam("url") String url); } @Test public void service22GetBytes() { final byte[] bytes = createService(Service22.class).getBytes("http: assertNotNull(bytes); assertEquals(27, bytes.length); } @Host("http: @ServiceInterface(name = "Service23") interface Service23 { @Get("bytes/28") byte[] getBytes(); } @Test public void service23GetBytes() { final byte[] bytes = createService(Service23.class).getBytes(); assertNotNull(bytes); assertEquals(28, bytes.length); } @Host("http: @ServiceInterface(name = "Service24") interface Service24 { @Put("put") HttpBinJSON put(@HeaderParam("ABC") Map<String, String> headerCollection); } @Test public void service24Put() { final Map<String, String> headerCollection = new HashMap<>(); headerCollection.put("DEF", "GHIJ"); headerCollection.put("123", "45"); final HttpBinJSON result = createService(Service24.class) .put(headerCollection); assertNotNull(result.headers()); final HttpHeaders resultHeaders = new HttpHeaders().setAll(result.headers()); assertEquals("GHIJ", resultHeaders.getValue("ABCDEF")); assertEquals("45", resultHeaders.getValue("ABC123")); } @Host("http: @ServiceInterface(name = "Service26") interface Service26 { @Post("post") HttpBinFormDataJSON postForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam("custemail") String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); @Post("post") HttpBinFormDataJSON postEncodedForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam(value = "custemail", encoded = true) String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); } @Test public void postUrlForm() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo%40bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Test public void postUrlFormEncoded() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postEncodedForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo@bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Host("http: @ServiceInterface(name = "Service27") interface Service27 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions requestOptions); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength, RequestOptions requestOptions); } @Test public void requestOptionsChangesBody() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("24"))); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("24", response.data()); } @Test public void requestOptionsChangesBodyAndContentLength() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("4242")) .setHeader("Content-Length", "4")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("4242", response.data()); assertEquals("4", response.getHeaderValue("Content-Length")); } @Test public void requestOptionsAddAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue", response.getHeaderValue("randomHeader")); } @Test public void requestOptionsSetsAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue") .setHeader("randomHeader", "randomValue2")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue2", response.getHeaderValue("randomHeader")); } protected <T> T createService(Class<T> serviceClass) { final HttpClient httpClient = createHttpClient(); return createService(serviceClass, httpClient); } protected <T> T createService(Class<T> serviceClass, HttpClient httpClient) { final HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(new PortPolicy(getWireMockPort(), true)) .httpClient(httpClient) .build(); return RestProxy.create(serviceClass, httpPipeline); } private static void assertMatchWithHttpOrHttps(String url1, String url2) { final String s1 = "http: if (s1.equalsIgnoreCase(url2)) { return; } final String s2 = "https: if (s2.equalsIgnoreCase(url2)) { return; } fail("'" + url2 + "' does not match with '" + s1 + "' or '" + s2 + "'."); } }
class RestProxyTests { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; /** * Get the HTTP client that will be used for each test. This will be called once per test. * * @return The HTTP client to use for each test. */ protected abstract HttpClient createHttpClient(); /** * Get the dynamic port the WireMock server is using to properly route the request. * * @return The HTTP port WireMock is using. */ protected abstract int getWireMockPort(); @Host("http: @ServiceInterface(name = "Service1") private interface Service1 { @Get("bytes/100") @ExpectedResponses({200}) byte[] getByteArray(); @Get("bytes/100") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(); @Get("bytes/100") Mono<byte[]> getByteArrayAsyncWithNoExpectedResponses(); } @Test public void syncRequestWithByteArrayReturnType() { final byte[] result = createService(Service1.class).getByteArray(); assertNotNull(result); assertEquals(100, result.length); } @Test public void asyncRequestWithByteArrayReturnType() { StepVerifier.create(createService(Service1.class).getByteArrayAsync()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void getByteArrayAsyncWithNoExpectedResponses() { StepVerifier.create(createService(Service1.class).getByteArrayAsyncWithNoExpectedResponses()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service2") private interface Service2 { @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) byte[] getByteArray(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); } @Test public void syncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 100); assertNotNull(result); assertEquals(result.length, 100); } @Test public void asyncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { StepVerifier.create(createService(Service2.class).getByteArrayAsync("localhost", 100)) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void syncRequestWithEmptyByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 0); assertNull(result); } @Host("http: @ServiceInterface(name = "Service3") private interface Service3 { @Get("bytes/100") @ExpectedResponses({200}) void getNothing(); @Get("bytes/100") @ExpectedResponses({200}) Mono<Void> getNothingAsync(); } @Test public void syncGetRequestWithNoReturn() { assertDoesNotThrow(() -> createService(Service3.class).getNothing()); } @Test public void asyncGetRequestWithNoReturn() { StepVerifier.create(createService(Service3.class).getNothingAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service5") private interface Service5 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(); @Get("anything/with+plus") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPlus(); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPathParam(@PathParam("path") String pathParam); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncodedPathParam(@PathParam(value = "path", encoded = true) String pathParam); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(); } @Test public void syncGetRequestWithAnything() { final HttpBinJSON json = createService(Service5.class).getAnything(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); } @Test public void syncGetRequestWithAnythingWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPlus(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+plus", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithSpace() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with path param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPercent20() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with%20path%20param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void asyncGetRequestWithAnything() { StepVerifier.create(createService(Service5.class).getAnythingAsync()) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service6") private interface Service6 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@QueryParam("a") String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncoded(@QueryParam(value = "a", encoded = true) String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@QueryParam("a") String a, @QueryParam("b") int b); } @Test public void syncGetRequestWithQueryParametersAndAnything() { final HttpBinJSON json = createService(Service6.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnything("A%20Z", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A%2520Z&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithEncodedWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnythingWithEncoded("x%20y", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=x y&b=15", json.url()); } @Test public void asyncGetRequestWithQueryParametersAndAnything() { StepVerifier.create(createService(Service6.class).getAnythingAsync("A", 15)) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url())) .verifyComplete(); } @Test public void syncGetRequestWithNullQueryParameter() { final HttpBinJSON json = createService(Service6.class).getAnything(null, 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?b=15", json.url()); } @Host("http: @ServiceInterface(name = "Service7") private interface Service7 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@HeaderParam("a") String a, @HeaderParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@HeaderParam("a") String a, @HeaderParam("b") int b); } @Test public void syncGetRequestWithHeaderParametersAndAnythingReturn() { final HttpBinJSON json = createService(Service7.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Test public void asyncGetRequestWithHeaderParametersAndAnything() { StepVerifier.create(createService(Service7.class).getAnythingAsync("A", 15)) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); }) .verifyComplete(); } @Test public void syncGetRequestWithNullHeader() { final HttpBinJSON json = createService(Service7.class).getAnything(null, 15); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertNull(headers.getValue("A")); assertArrayEquals(null, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Host("http: @ServiceInterface(name = "Service8") private interface Service8 { @Post("post") @ExpectedResponses({200}) HttpBinJSON post(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); @Post("post") @ExpectedResponses({200}) Mono<HttpBinJSON> postAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); } @Test public void syncPostRequestWithStringBody() { final HttpBinJSON json = createService(Service8.class).post("I'm a post body!"); assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); } @Test public void asyncPostRequestWithStringBody() { StepVerifier.create(createService(Service8.class).postAsync("I'm a post body!")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); }) .verifyComplete(); } @Test public void syncPostRequestWithNullBody() { final HttpBinJSON result = createService(Service8.class).post(null); assertEquals("", result.data()); } @Host("http: @ServiceInterface(name = "Service9") private interface Service9 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) Flux<ByteBuffer> body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) BinaryData body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({201}) HttpBinJSON putWithUnexpectedResponse(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) Mono<HttpBinJSON> putWithUnexpectedResponseAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) HttpBinJSON putWithUnexpectedResponseAndDeterminedExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndDeterminedExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndNoFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); } @Test public void syncPutRequestWithIntBody() { final HttpBinJSON json = createService(Service9.class).put(42); assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); } @Test public void asyncPutRequestWithIntBody() { StepVerifier.create(createService(Service9.class).putAsync(42)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); }).verifyComplete(); } @Test public void syncPutRequestWithBodyAndEqualContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); final HttpBinJSON json = createService(Service9.class).putBodyAndContentLength(body, 4L); assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); } @Test public void syncPutRequestWithBodyLessThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 5L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("less than")); } @Test public void syncPutRequestWithBodyMoreThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 3L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("more than")); } @Test public void asyncPutRequestWithBodyAndEqualContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 4L)) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBodyAndLessThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 5L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBodyAndMoreThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 3L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndEqualContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 4L))) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void syncPutRequestWithUnexpectedResponse() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponse("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponse() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException); HttpResponseException exception = (HttpResponseException) throwable; assertNotNull(exception.getValue()); assertTrue(exception.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) exception.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Test public void syncPutRequestWithUnexpectedResponseAndExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException myRestException = (MyRestException) throwable; assertNotNull(myRestException.getValue()); assertEquals("I'm the body!", myRestException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); HttpResponseException responseException = (HttpResponseException) throwable; assertNotNull(responseException.getValue()); assertTrue(responseException.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) responseException.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Host("http: @ServiceInterface(name = "Service10") private interface Service10 { @Head("anything") @ExpectedResponses({200}) Response<Void> head(); @Head("anything") @ExpectedResponses({200}) boolean headBoolean(); @Head("anything") @ExpectedResponses({200}) void voidHead(); @Head("anything") @ExpectedResponses({200}) Mono<Response<Void>> headAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Boolean> headBooleanAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Void> completableHeadAsync(); } @Test public void syncHeadRequest() { final Void body = createService(Service10.class).head().getValue(); assertNull(body); } @Test public void syncHeadBooleanRequest() { final boolean result = createService(Service10.class).headBoolean(); assertTrue(result); } @Test public void syncVoidHeadRequest() { createService(Service10.class) .voidHead(); } @Test public void asyncHeadRequest() { StepVerifier.create(createService(Service10.class).headAsync()) .assertNext(response -> assertNull(response.getValue())) .verifyComplete(); } @Test public void asyncHeadBooleanRequest() { StepVerifier.create(createService(Service10.class).headBooleanAsync()) .assertNext(Assertions::assertTrue) .verifyComplete(); } @Test public void asyncCompletableHeadRequest() { StepVerifier.create(createService(Service10.class).completableHeadAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service11") private interface Service11 { @Delete("delete") @ExpectedResponses({200}) HttpBinJSON delete(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); @Delete("delete") @ExpectedResponses({200}) Mono<HttpBinJSON> deleteAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); } @Test public void syncDeleteRequest() { final HttpBinJSON json = createService(Service11.class).delete(false); assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); } @Test public void asyncDeleteRequest() { StepVerifier.create(createService(Service11.class).deleteAsync(false)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service12") private interface Service12 { @Patch("patch") @ExpectedResponses({200}) HttpBinJSON patch(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); @Patch("patch") @ExpectedResponses({200}) Mono<HttpBinJSON> patchAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); } @Test public void syncPatchRequest() { final HttpBinJSON json = createService(Service12.class).patch("body-contents"); assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); } @Test public void asyncPatchRequest() { StepVerifier.create(createService(Service12.class).patchAsync("body-contents")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service13") private interface Service13 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) Mono<HttpBinJSON> getAsync(); } @Test public void syncHeadersRequest() { final HttpBinJSON json = createService(Service13.class).get(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); assertEquals("My,Header,Value", headers.getValue("MyOtherHeader")); assertArrayEquals(new String[]{"My", "Header", "Value"}, headers.getValues("MyOtherHeader")); } @Test public void asyncHeadersRequest() { StepVerifier.create(createService(Service13.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service14") private interface Service14 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) Mono<HttpBinJSON> getAsync(); } @Test public void asyncHttpsHeadersRequest() { StepVerifier.create(createService(Service14.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service16") private interface Service16 { @Put("put") @ExpectedResponses({200}) HttpBinJSON putByteArray(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putByteArrayAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); } @Test public void service16Put() { final Service16 service16 = createService(Service16.class); final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; final HttpBinJSON httpBinJSON = service16.putByteArray(expectedBytes); assertTrue(httpBinJSON.data() instanceof String); final String base64String = (String) httpBinJSON.data(); final byte[] actualBytes = base64String.getBytes(); assertArrayEquals(expectedBytes, actualBytes); } @Test public void service16PutAsync() { final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; StepVerifier.create(createService(Service16.class).putByteArrayAsync(expectedBytes)) .assertNext(json -> { assertTrue(json.data() instanceof String); assertArrayEquals(expectedBytes, ((String) json.data()).getBytes()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service17") private interface Service17 { @Get("get") @ExpectedResponses({200}) HttpBinJSON get(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); @Get("get") @ExpectedResponses({200}) Mono<HttpBinJSON> getAsync(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); } @Test public void syncRequestWithMultipleHostParams() { final HttpBinJSON result = createService(Service17.class).get("local", "host"); assertNotNull(result); assertMatchWithHttpOrHttps("localhost/get", result.url()); } @Test public void asyncRequestWithMultipleHostParams() { StepVerifier.create(createService(Service17.class).getAsync("local", "host")) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/get", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service18") private interface Service18 { @Get("status/200") void getStatus200(); @Get("status/200") @ExpectedResponses({200}) void getStatus200WithExpectedResponse200(); @Get("status/300") void getStatus300(); @Get("status/300") @ExpectedResponses({300}) void getStatus300WithExpectedResponse300(); @Get("status/400") void getStatus400(); @Get("status/400") @ExpectedResponses({400}) void getStatus400WithExpectedResponse400(); @Get("status/500") void getStatus500(); @Get("status/500") @ExpectedResponses({500}) void getStatus500WithExpectedResponse500(); } @Test public void service18GetStatus200() { createService(Service18.class).getStatus200(); } @Test public void service18GetStatus200WithExpectedResponse200() { assertDoesNotThrow(() -> createService(Service18.class).getStatus200WithExpectedResponse200()); } @Test public void service18GetStatus300() { createService(Service18.class).getStatus300(); } @Test public void service18GetStatus300WithExpectedResponse300() { assertDoesNotThrow(() -> createService(Service18.class).getStatus300WithExpectedResponse300()); } @Test public void service18GetStatus400() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus400()); } @Test public void service18GetStatus400WithExpectedResponse400() { assertDoesNotThrow(() -> createService(Service18.class).getStatus400WithExpectedResponse400()); } @Test public void service18GetStatus500() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus500()); } @Test public void service18GetStatus500WithExpectedResponse500() { assertDoesNotThrow(() -> createService(Service18.class).getStatus500WithExpectedResponse500()); } @Host("http: @ServiceInterface(name = "Service19") private interface Service19 { @Put("put") HttpBinJSON putWithNoContentTypeAndStringBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithNoContentTypeAndByteArrayBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithHeaderApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") @Headers({"Content-Type: application/json"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") @Headers({"Content-Type: application/json; charset=utf-8"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_JSON + "; charset=utf-8") String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody("hello"); assertEquals("hello", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithNoContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("soups and stuff", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Host("http: @ServiceInterface(name = "Service20") private interface Service20 { @Get("bytes/100") ResponseBase<HttpBinHeaders, Void> getBytes100OnlyHeaders(); @Get("bytes/100") ResponseBase<HttpHeaders, Void> getBytes100OnlyRawHeaders(); @Get("bytes/100") ResponseBase<HttpBinHeaders, byte[]> getBytes100BodyAndHeaders(); @Put("put") ResponseBase<HttpBinHeaders, Void> putOnlyHeaders(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") ResponseBase<HttpBinHeaders, HttpBinJSON> putBodyAndHeaders( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Get("bytes/100") ResponseBase<Void, Void> getBytesOnlyStatus(); @Get("bytes/100") Response<Void> getVoidResponse(); @Put("put") Response<HttpBinJSON> putBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); } @Test public void service20GetBytes100OnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).getBytes100OnlyHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytes100BodyAndHeaders() { final ResponseBase<HttpBinHeaders, byte[]> response = createService(Service20.class).getBytes100BodyAndHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final byte[] body = response.getValue(); assertNotNull(body); assertEquals(100, body.length); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytesOnlyStatus() { final Response<Void> response = createService(Service20.class).getBytesOnlyStatus(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetBytesOnlyHeaders() { final Response<Void> response = createService(Service20.class).getBytes100OnlyRawHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertNotNull(response.getHeaders()); assertNotEquals(0, response.getHeaders().getSize()); } @Test public void service20PutOnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).putOnlyHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20PutBodyAndHeaders() { final ResponseBase<HttpBinHeaders, HttpBinJSON> response = createService(Service20.class).putBodyAndHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetVoidResponse() { final Response<Void> response = createService(Service20.class).getVoidResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetResponseBody() { final Response<HttpBinJSON> response = createService(Service20.class).putBody("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpHeaders headers = response.getHeaders(); assertNotNull(headers); } @Host("http: @ServiceInterface(name = "UnexpectedOKService") interface UnexpectedOKService { @Get("/bytes/1024") @ExpectedResponses({400}) StreamResponse getBytes(); } @Test public void unexpectedHTTPOK() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(UnexpectedOKService.class).getBytes()); assertEquals("Status code 200, (1024-byte body)", e.getMessage()); } @Host("https: @ServiceInterface(name = "Service21") private interface Service21 { @Get("http: @ExpectedResponses({200}) byte[] getBytes100(); } @Test public void service21GetBytes100() { final byte[] bytes = createService(Service21.class).getBytes100(); assertNotNull(bytes); assertEquals(100, bytes.length); } @Host("http: @ServiceInterface(name = "DownloadService") interface DownloadService { @Get("/bytes/30720") StreamResponse getBytes(Context context); @Get("/bytes/30720") Mono<StreamResponse> getBytesAsync(Context context); @Get("/bytes/30720") Flux<ByteBuffer> getBytesFlux(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void simpleDownloadTestAsync(Context context) { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> response.getValue().map(ByteBuffer::remaining) .reduce(0, Integer::sum) .doFinally(ignore -> response.close()))) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))) .doFinally(ignore -> response.close()))) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBody(Context context) throws IOException { try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); streamResponse.transferValueTo(Channels.newChannel(bos)); assertEquals(streamResponse.getHeaders().getValue("ETag"), MessageDigestUtils.md5(bos.toByteArray())); } Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { StepVerifier.create(Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).then(Mono.fromCallable(() -> MessageDigestUtils.md5(Files.readAllBytes(tempFile))))) .assertNext(hash -> assertEquals(streamResponse.getHeaders().getValue("ETag"), hash)) .verifyComplete(); } } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBodyAsync(Context context) throws IOException { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .publishOn(Schedulers.boundedElastic()) .map(streamResponse -> { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { streamResponse.transferValueTo(Channels.newChannel(bos)); } catch (IOException e) { throw Exceptions.propagate(e); } finally { streamResponse.close(); } return Tuples.of(streamResponse.getHeaders().getValue("Etag"), MessageDigestUtils.md5(bos.toByteArray())); })) .assertNext(hashTuple -> assertEquals(hashTuple.getT1(), hashTuple.getT2())) .verifyComplete(); Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(streamResponse -> Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).doFinally(ignored -> streamResponse.close()) .then(Mono.just(streamResponse.getHeaders().getValue("ETag"))))) .assertNext(hash -> { try { assertEquals(hash, MessageDigestUtils.md5(Files.readAllBytes(tempFile))); } catch (IOException e) { Exceptions.propagate(e); } }) .verifyComplete(); } public static Stream<Arguments> downloadTestArgumentProvider() { return Stream.of( Arguments.of(Named.named("default", Context.NONE)), Arguments.of(Named.named("sync proxy enabled", Context.NONE .addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true)))); } @Test public void rawFluxDownloadTest() { StepVerifier.create(createService(DownloadService.class).getBytesFlux() .map(ByteBuffer::remaining).reduce(0, Integer::sum)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface FluxUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") Flux<ByteBuffer> content, @HeaderParam("Content-Length") long contentLength); } @Test public void fluxUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); Flux<ByteBuffer> stream = FluxUtil.readFile(AsynchronousFileChannel.open(filePath)); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(FluxUploadService.class, httpPipeline).put(stream, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Test public void segmentUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(filePath, StandardOpenOption.READ); Response<HttpBinJSON> response = createService(FluxUploadService.class) .put(FluxUtil.readFile(fileChannel, 4, 15), 15); assertEquals("quick brown fox", response.getValue().data()); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface BinaryDataUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") BinaryData content, @HeaderParam("Content-Length") long contentLength); } @Test public void binaryDataUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); BinaryData data = BinaryData.fromFile(filePath); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(BinaryDataUploadService.class, httpPipeline).put(data, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Host("{url}") @ServiceInterface(name = "Service22") interface Service22 { @Get("/") byte[] getBytes(@HostParam("url") String url); } @Test public void service22GetBytes() { final byte[] bytes = createService(Service22.class).getBytes("http: assertNotNull(bytes); assertEquals(27, bytes.length); } @Host("http: @ServiceInterface(name = "Service23") interface Service23 { @Get("bytes/28") byte[] getBytes(); } @Test public void service23GetBytes() { final byte[] bytes = createService(Service23.class).getBytes(); assertNotNull(bytes); assertEquals(28, bytes.length); } @Host("http: @ServiceInterface(name = "Service24") interface Service24 { @Put("put") HttpBinJSON put(@HeaderParam("ABC") Map<String, String> headerCollection); } @Test public void service24Put() { final Map<String, String> headerCollection = new HashMap<>(); headerCollection.put("DEF", "GHIJ"); headerCollection.put("123", "45"); final HttpBinJSON result = createService(Service24.class) .put(headerCollection); assertNotNull(result.headers()); final HttpHeaders resultHeaders = new HttpHeaders().setAll(result.headers()); assertEquals("GHIJ", resultHeaders.getValue("ABCDEF")); assertEquals("45", resultHeaders.getValue("ABC123")); } @Host("http: @ServiceInterface(name = "Service26") interface Service26 { @Post("post") HttpBinFormDataJSON postForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam("custemail") String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); @Post("post") HttpBinFormDataJSON postEncodedForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam(value = "custemail", encoded = true) String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); } @Test public void postUrlForm() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo%40bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Test public void postUrlFormEncoded() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postEncodedForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo@bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Host("http: @ServiceInterface(name = "Service27") interface Service27 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions requestOptions); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength, RequestOptions requestOptions); } @Test public void requestOptionsChangesBody() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("24"))); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("24", response.data()); } @Test public void requestOptionsChangesBodyAndContentLength() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("4242")) .setHeader("Content-Length", "4")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("4242", response.data()); assertEquals("4", response.getHeaderValue("Content-Length")); } @Test public void requestOptionsAddAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue", response.getHeaderValue("randomHeader")); } @Test public void requestOptionsSetsAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue") .setHeader("randomHeader", "randomValue2")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue2", response.getHeaderValue("randomHeader")); } protected <T> T createService(Class<T> serviceClass) { final HttpClient httpClient = createHttpClient(); return createService(serviceClass, httpClient); } protected <T> T createService(Class<T> serviceClass, HttpClient httpClient) { final HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(new PortPolicy(getWireMockPort(), true)) .httpClient(httpClient) .build(); return RestProxy.create(serviceClass, httpPipeline); } private static void assertMatchWithHttpOrHttps(String url1, String url2) { final String s1 = "http: if (s1.equalsIgnoreCase(url2)) { return; } final String s2 = "https: if (s2.equalsIgnoreCase(url2)) { return; } fail("'" + url2 + "' does not match with '" + s1 + "' or '" + s2 + "'."); } }
I did attempt that, but figured that the test is a bit easier to understand if they're separated, i.e. the reduction logic is simpler this way.
public void simpleDownloadTest(Context context) { StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> response.getValue().map(ByteBuffer::remaining).reduce(0, Integer::sum), StreamResponse::close)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))), StreamResponse::close)) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); }
StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context),
public void simpleDownloadTest(Context context) { StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> response.getValue().map(ByteBuffer::remaining).reduce(0, Integer::sum), StreamResponse::close)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(Flux.using(() -> createService(DownloadService.class).getBytes(context), response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))), StreamResponse::close)) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); }
class RestProxyTests { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; /** * Get the HTTP client that will be used for each test. This will be called once per test. * * @return The HTTP client to use for each test. */ protected abstract HttpClient createHttpClient(); /** * Get the dynamic port the WireMock server is using to properly route the request. * * @return The HTTP port WireMock is using. */ protected abstract int getWireMockPort(); @Host("http: @ServiceInterface(name = "Service1") private interface Service1 { @Get("bytes/100") @ExpectedResponses({200}) byte[] getByteArray(); @Get("bytes/100") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(); @Get("bytes/100") Mono<byte[]> getByteArrayAsyncWithNoExpectedResponses(); } @Test public void syncRequestWithByteArrayReturnType() { final byte[] result = createService(Service1.class).getByteArray(); assertNotNull(result); assertEquals(100, result.length); } @Test public void asyncRequestWithByteArrayReturnType() { StepVerifier.create(createService(Service1.class).getByteArrayAsync()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void getByteArrayAsyncWithNoExpectedResponses() { StepVerifier.create(createService(Service1.class).getByteArrayAsyncWithNoExpectedResponses()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service2") private interface Service2 { @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) byte[] getByteArray(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); } @Test public void syncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 100); assertNotNull(result); assertEquals(result.length, 100); } @Test public void asyncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { StepVerifier.create(createService(Service2.class).getByteArrayAsync("localhost", 100)) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void syncRequestWithEmptyByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 0); assertNull(result); } @Host("http: @ServiceInterface(name = "Service3") private interface Service3 { @Get("bytes/100") @ExpectedResponses({200}) void getNothing(); @Get("bytes/100") @ExpectedResponses({200}) Mono<Void> getNothingAsync(); } @Test public void syncGetRequestWithNoReturn() { assertDoesNotThrow(() -> createService(Service3.class).getNothing()); } @Test public void asyncGetRequestWithNoReturn() { StepVerifier.create(createService(Service3.class).getNothingAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service5") private interface Service5 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(); @Get("anything/with+plus") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPlus(); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPathParam(@PathParam("path") String pathParam); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncodedPathParam(@PathParam(value = "path", encoded = true) String pathParam); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(); } @Test public void syncGetRequestWithAnything() { final HttpBinJSON json = createService(Service5.class).getAnything(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); } @Test public void syncGetRequestWithAnythingWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPlus(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+plus", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithSpace() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with path param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPercent20() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with%20path%20param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void asyncGetRequestWithAnything() { StepVerifier.create(createService(Service5.class).getAnythingAsync()) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service6") private interface Service6 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@QueryParam("a") String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncoded(@QueryParam(value = "a", encoded = true) String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@QueryParam("a") String a, @QueryParam("b") int b); } @Test public void syncGetRequestWithQueryParametersAndAnything() { final HttpBinJSON json = createService(Service6.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnything("A%20Z", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A%2520Z&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithEncodedWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnythingWithEncoded("x%20y", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=x y&b=15", json.url()); } @Test public void asyncGetRequestWithQueryParametersAndAnything() { StepVerifier.create(createService(Service6.class).getAnythingAsync("A", 15)) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url())) .verifyComplete(); } @Test public void syncGetRequestWithNullQueryParameter() { final HttpBinJSON json = createService(Service6.class).getAnything(null, 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?b=15", json.url()); } @Host("http: @ServiceInterface(name = "Service7") private interface Service7 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@HeaderParam("a") String a, @HeaderParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@HeaderParam("a") String a, @HeaderParam("b") int b); } @Test public void syncGetRequestWithHeaderParametersAndAnythingReturn() { final HttpBinJSON json = createService(Service7.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Test public void asyncGetRequestWithHeaderParametersAndAnything() { StepVerifier.create(createService(Service7.class).getAnythingAsync("A", 15)) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); }) .verifyComplete(); } @Test public void syncGetRequestWithNullHeader() { final HttpBinJSON json = createService(Service7.class).getAnything(null, 15); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertNull(headers.getValue("A")); assertArrayEquals(null, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Host("http: @ServiceInterface(name = "Service8") private interface Service8 { @Post("post") @ExpectedResponses({200}) HttpBinJSON post(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); @Post("post") @ExpectedResponses({200}) Mono<HttpBinJSON> postAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); } @Test public void syncPostRequestWithStringBody() { final HttpBinJSON json = createService(Service8.class).post("I'm a post body!"); assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); } @Test public void asyncPostRequestWithStringBody() { StepVerifier.create(createService(Service8.class).postAsync("I'm a post body!")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); }) .verifyComplete(); } @Test public void syncPostRequestWithNullBody() { final HttpBinJSON result = createService(Service8.class).post(null); assertEquals("", result.data()); } @Host("http: @ServiceInterface(name = "Service9") private interface Service9 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) Flux<ByteBuffer> body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) BinaryData body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({201}) HttpBinJSON putWithUnexpectedResponse(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) Mono<HttpBinJSON> putWithUnexpectedResponseAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) HttpBinJSON putWithUnexpectedResponseAndDeterminedExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndDeterminedExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndNoFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); } @Test public void syncPutRequestWithIntBody() { final HttpBinJSON json = createService(Service9.class).put(42); assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); } @Test public void asyncPutRequestWithIntBody() { StepVerifier.create(createService(Service9.class).putAsync(42)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); }).verifyComplete(); } @Test public void syncPutRequestWithBodyAndEqualContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); final HttpBinJSON json = createService(Service9.class).putBodyAndContentLength(body, 4L); assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); } @Test public void syncPutRequestWithBodyLessThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 5L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("less than")); } @Test public void syncPutRequestWithBodyMoreThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 3L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("more than")); } @Test public void asyncPutRequestWithBodyAndEqualContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 4L)) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBodyAndLessThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 5L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBodyAndMoreThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 3L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndEqualContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 4L))) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void syncPutRequestWithUnexpectedResponse() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponse("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponse() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException); HttpResponseException exception = (HttpResponseException) throwable; assertNotNull(exception.getValue()); assertTrue(exception.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) exception.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Test public void syncPutRequestWithUnexpectedResponseAndExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException myRestException = (MyRestException) throwable; assertNotNull(myRestException.getValue()); assertEquals("I'm the body!", myRestException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); HttpResponseException responseException = (HttpResponseException) throwable; assertNotNull(responseException.getValue()); assertTrue(responseException.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) responseException.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Host("http: @ServiceInterface(name = "Service10") private interface Service10 { @Head("anything") @ExpectedResponses({200}) Response<Void> head(); @Head("anything") @ExpectedResponses({200}) boolean headBoolean(); @Head("anything") @ExpectedResponses({200}) void voidHead(); @Head("anything") @ExpectedResponses({200}) Mono<Response<Void>> headAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Boolean> headBooleanAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Void> completableHeadAsync(); } @Test public void syncHeadRequest() { final Void body = createService(Service10.class).head().getValue(); assertNull(body); } @Test public void syncHeadBooleanRequest() { final boolean result = createService(Service10.class).headBoolean(); assertTrue(result); } @Test public void syncVoidHeadRequest() { createService(Service10.class) .voidHead(); } @Test public void asyncHeadRequest() { StepVerifier.create(createService(Service10.class).headAsync()) .assertNext(response -> assertNull(response.getValue())) .verifyComplete(); } @Test public void asyncHeadBooleanRequest() { StepVerifier.create(createService(Service10.class).headBooleanAsync()) .assertNext(Assertions::assertTrue) .verifyComplete(); } @Test public void asyncCompletableHeadRequest() { StepVerifier.create(createService(Service10.class).completableHeadAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service11") private interface Service11 { @Delete("delete") @ExpectedResponses({200}) HttpBinJSON delete(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); @Delete("delete") @ExpectedResponses({200}) Mono<HttpBinJSON> deleteAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); } @Test public void syncDeleteRequest() { final HttpBinJSON json = createService(Service11.class).delete(false); assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); } @Test public void asyncDeleteRequest() { StepVerifier.create(createService(Service11.class).deleteAsync(false)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service12") private interface Service12 { @Patch("patch") @ExpectedResponses({200}) HttpBinJSON patch(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); @Patch("patch") @ExpectedResponses({200}) Mono<HttpBinJSON> patchAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); } @Test public void syncPatchRequest() { final HttpBinJSON json = createService(Service12.class).patch("body-contents"); assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); } @Test public void asyncPatchRequest() { StepVerifier.create(createService(Service12.class).patchAsync("body-contents")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service13") private interface Service13 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) Mono<HttpBinJSON> getAsync(); } @Test public void syncHeadersRequest() { final HttpBinJSON json = createService(Service13.class).get(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); assertEquals("My,Header,Value", headers.getValue("MyOtherHeader")); assertArrayEquals(new String[]{"My", "Header", "Value"}, headers.getValues("MyOtherHeader")); } @Test public void asyncHeadersRequest() { StepVerifier.create(createService(Service13.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service14") private interface Service14 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) Mono<HttpBinJSON> getAsync(); } @Test public void asyncHttpsHeadersRequest() { StepVerifier.create(createService(Service14.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service16") private interface Service16 { @Put("put") @ExpectedResponses({200}) HttpBinJSON putByteArray(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putByteArrayAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); } @Test public void service16Put() { final Service16 service16 = createService(Service16.class); final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; final HttpBinJSON httpBinJSON = service16.putByteArray(expectedBytes); assertTrue(httpBinJSON.data() instanceof String); final String base64String = (String) httpBinJSON.data(); final byte[] actualBytes = base64String.getBytes(); assertArrayEquals(expectedBytes, actualBytes); } @Test public void service16PutAsync() { final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; StepVerifier.create(createService(Service16.class).putByteArrayAsync(expectedBytes)) .assertNext(json -> { assertTrue(json.data() instanceof String); assertArrayEquals(expectedBytes, ((String) json.data()).getBytes()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service17") private interface Service17 { @Get("get") @ExpectedResponses({200}) HttpBinJSON get(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); @Get("get") @ExpectedResponses({200}) Mono<HttpBinJSON> getAsync(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); } @Test public void syncRequestWithMultipleHostParams() { final HttpBinJSON result = createService(Service17.class).get("local", "host"); assertNotNull(result); assertMatchWithHttpOrHttps("localhost/get", result.url()); } @Test public void asyncRequestWithMultipleHostParams() { StepVerifier.create(createService(Service17.class).getAsync("local", "host")) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/get", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service18") private interface Service18 { @Get("status/200") void getStatus200(); @Get("status/200") @ExpectedResponses({200}) void getStatus200WithExpectedResponse200(); @Get("status/300") void getStatus300(); @Get("status/300") @ExpectedResponses({300}) void getStatus300WithExpectedResponse300(); @Get("status/400") void getStatus400(); @Get("status/400") @ExpectedResponses({400}) void getStatus400WithExpectedResponse400(); @Get("status/500") void getStatus500(); @Get("status/500") @ExpectedResponses({500}) void getStatus500WithExpectedResponse500(); } @Test public void service18GetStatus200() { createService(Service18.class).getStatus200(); } @Test public void service18GetStatus200WithExpectedResponse200() { assertDoesNotThrow(() -> createService(Service18.class).getStatus200WithExpectedResponse200()); } @Test public void service18GetStatus300() { createService(Service18.class).getStatus300(); } @Test public void service18GetStatus300WithExpectedResponse300() { assertDoesNotThrow(() -> createService(Service18.class).getStatus300WithExpectedResponse300()); } @Test public void service18GetStatus400() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus400()); } @Test public void service18GetStatus400WithExpectedResponse400() { assertDoesNotThrow(() -> createService(Service18.class).getStatus400WithExpectedResponse400()); } @Test public void service18GetStatus500() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus500()); } @Test public void service18GetStatus500WithExpectedResponse500() { assertDoesNotThrow(() -> createService(Service18.class).getStatus500WithExpectedResponse500()); } @Host("http: @ServiceInterface(name = "Service19") private interface Service19 { @Put("put") HttpBinJSON putWithNoContentTypeAndStringBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithNoContentTypeAndByteArrayBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithHeaderApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") @Headers({"Content-Type: application/json"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") @Headers({"Content-Type: application/json; charset=utf-8"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_JSON + "; charset=utf-8") String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody("hello"); assertEquals("hello", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithNoContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("soups and stuff", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Host("http: @ServiceInterface(name = "Service20") private interface Service20 { @Get("bytes/100") ResponseBase<HttpBinHeaders, Void> getBytes100OnlyHeaders(); @Get("bytes/100") ResponseBase<HttpHeaders, Void> getBytes100OnlyRawHeaders(); @Get("bytes/100") ResponseBase<HttpBinHeaders, byte[]> getBytes100BodyAndHeaders(); @Put("put") ResponseBase<HttpBinHeaders, Void> putOnlyHeaders(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") ResponseBase<HttpBinHeaders, HttpBinJSON> putBodyAndHeaders( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Get("bytes/100") ResponseBase<Void, Void> getBytesOnlyStatus(); @Get("bytes/100") Response<Void> getVoidResponse(); @Put("put") Response<HttpBinJSON> putBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); } @Test public void service20GetBytes100OnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).getBytes100OnlyHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytes100BodyAndHeaders() { final ResponseBase<HttpBinHeaders, byte[]> response = createService(Service20.class).getBytes100BodyAndHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final byte[] body = response.getValue(); assertNotNull(body); assertEquals(100, body.length); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytesOnlyStatus() { final Response<Void> response = createService(Service20.class).getBytesOnlyStatus(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetBytesOnlyHeaders() { final Response<Void> response = createService(Service20.class).getBytes100OnlyRawHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertNotNull(response.getHeaders()); assertNotEquals(0, response.getHeaders().getSize()); } @Test public void service20PutOnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).putOnlyHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20PutBodyAndHeaders() { final ResponseBase<HttpBinHeaders, HttpBinJSON> response = createService(Service20.class).putBodyAndHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetVoidResponse() { final Response<Void> response = createService(Service20.class).getVoidResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetResponseBody() { final Response<HttpBinJSON> response = createService(Service20.class).putBody("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpHeaders headers = response.getHeaders(); assertNotNull(headers); } @Host("http: @ServiceInterface(name = "UnexpectedOKService") interface UnexpectedOKService { @Get("/bytes/1024") @ExpectedResponses({400}) StreamResponse getBytes(); } @Test public void unexpectedHTTPOK() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(UnexpectedOKService.class).getBytes()); assertEquals("Status code 200, (1024-byte body)", e.getMessage()); } @Host("https: @ServiceInterface(name = "Service21") private interface Service21 { @Get("http: @ExpectedResponses({200}) byte[] getBytes100(); } @Test public void service21GetBytes100() { final byte[] bytes = createService(Service21.class).getBytes100(); assertNotNull(bytes); assertEquals(100, bytes.length); } @Host("http: @ServiceInterface(name = "DownloadService") interface DownloadService { @Get("/bytes/30720") StreamResponse getBytes(Context context); @Get("/bytes/30720") Mono<StreamResponse> getBytesAsync(Context context); @Get("/bytes/30720") Flux<ByteBuffer> getBytesFlux(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void simpleDownloadTestAsync(Context context) { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> response.getValue().map(ByteBuffer::remaining) .reduce(0, Integer::sum) .doFinally(ignore -> response.close()))) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))) .doFinally(ignore -> response.close()))) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBody(Context context) throws IOException { try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); streamResponse.transferValueTo(Channels.newChannel(bos)); assertEquals(streamResponse.getHeaders().getValue("ETag"), MessageDigestUtils.md5(bos.toByteArray())); } Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { StepVerifier.create(Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).then(Mono.fromCallable(() -> MessageDigestUtils.md5(Files.readAllBytes(tempFile))))) .assertNext(hash -> assertEquals(streamResponse.getHeaders().getValue("ETag"), hash)) .verifyComplete(); } } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBodyAsync(Context context) throws IOException { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .publishOn(Schedulers.boundedElastic()) .map(streamResponse -> { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { streamResponse.transferValueTo(Channels.newChannel(bos)); } catch (IOException e) { throw Exceptions.propagate(e); } finally { streamResponse.close(); } return Tuples.of(streamResponse.getHeaders().getValue("Etag"), MessageDigestUtils.md5(bos.toByteArray())); })) .assertNext(hashTuple -> assertEquals(hashTuple.getT1(), hashTuple.getT2())) .verifyComplete(); Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(streamResponse -> Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).doFinally(ignored -> streamResponse.close()) .then(Mono.just(streamResponse.getHeaders().getValue("ETag"))))) .assertNext(hash -> { try { assertEquals(hash, MessageDigestUtils.md5(Files.readAllBytes(tempFile))); } catch (IOException e) { Exceptions.propagate(e); } }) .verifyComplete(); } public static Stream<Arguments> downloadTestArgumentProvider() { return Stream.of( Arguments.of(Named.named("default", Context.NONE)), Arguments.of(Named.named("sync proxy enabled", Context.NONE .addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true)))); } @Test public void rawFluxDownloadTest() { StepVerifier.create(createService(DownloadService.class).getBytesFlux() .map(ByteBuffer::remaining).reduce(0, Integer::sum)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface FluxUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") Flux<ByteBuffer> content, @HeaderParam("Content-Length") long contentLength); } @Test public void fluxUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); Flux<ByteBuffer> stream = FluxUtil.readFile(AsynchronousFileChannel.open(filePath)); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(FluxUploadService.class, httpPipeline).put(stream, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Test public void segmentUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(filePath, StandardOpenOption.READ); Response<HttpBinJSON> response = createService(FluxUploadService.class) .put(FluxUtil.readFile(fileChannel, 4, 15), 15); assertEquals("quick brown fox", response.getValue().data()); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface BinaryDataUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") BinaryData content, @HeaderParam("Content-Length") long contentLength); } @Test public void binaryDataUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); BinaryData data = BinaryData.fromFile(filePath); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(BinaryDataUploadService.class, httpPipeline).put(data, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Host("{url}") @ServiceInterface(name = "Service22") interface Service22 { @Get("/") byte[] getBytes(@HostParam("url") String url); } @Test public void service22GetBytes() { final byte[] bytes = createService(Service22.class).getBytes("http: assertNotNull(bytes); assertEquals(27, bytes.length); } @Host("http: @ServiceInterface(name = "Service23") interface Service23 { @Get("bytes/28") byte[] getBytes(); } @Test public void service23GetBytes() { final byte[] bytes = createService(Service23.class).getBytes(); assertNotNull(bytes); assertEquals(28, bytes.length); } @Host("http: @ServiceInterface(name = "Service24") interface Service24 { @Put("put") HttpBinJSON put(@HeaderParam("ABC") Map<String, String> headerCollection); } @Test public void service24Put() { final Map<String, String> headerCollection = new HashMap<>(); headerCollection.put("DEF", "GHIJ"); headerCollection.put("123", "45"); final HttpBinJSON result = createService(Service24.class) .put(headerCollection); assertNotNull(result.headers()); final HttpHeaders resultHeaders = new HttpHeaders().setAll(result.headers()); assertEquals("GHIJ", resultHeaders.getValue("ABCDEF")); assertEquals("45", resultHeaders.getValue("ABC123")); } @Host("http: @ServiceInterface(name = "Service26") interface Service26 { @Post("post") HttpBinFormDataJSON postForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam("custemail") String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); @Post("post") HttpBinFormDataJSON postEncodedForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam(value = "custemail", encoded = true) String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); } @Test public void postUrlForm() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo%40bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Test public void postUrlFormEncoded() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postEncodedForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo@bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Host("http: @ServiceInterface(name = "Service27") interface Service27 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions requestOptions); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength, RequestOptions requestOptions); } @Test public void requestOptionsChangesBody() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("24"))); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("24", response.data()); } @Test public void requestOptionsChangesBodyAndContentLength() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("4242")) .setHeader("Content-Length", "4")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("4242", response.data()); assertEquals("4", response.getHeaderValue("Content-Length")); } @Test public void requestOptionsAddAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue", response.getHeaderValue("randomHeader")); } @Test public void requestOptionsSetsAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue") .setHeader("randomHeader", "randomValue2")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue2", response.getHeaderValue("randomHeader")); } protected <T> T createService(Class<T> serviceClass) { final HttpClient httpClient = createHttpClient(); return createService(serviceClass, httpClient); } protected <T> T createService(Class<T> serviceClass, HttpClient httpClient) { final HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(new PortPolicy(getWireMockPort(), true)) .httpClient(httpClient) .build(); return RestProxy.create(serviceClass, httpPipeline); } private static void assertMatchWithHttpOrHttps(String url1, String url2) { final String s1 = "http: if (s1.equalsIgnoreCase(url2)) { return; } final String s2 = "https: if (s2.equalsIgnoreCase(url2)) { return; } fail("'" + url2 + "' does not match with '" + s1 + "' or '" + s2 + "'."); } }
class RestProxyTests { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; /** * Get the HTTP client that will be used for each test. This will be called once per test. * * @return The HTTP client to use for each test. */ protected abstract HttpClient createHttpClient(); /** * Get the dynamic port the WireMock server is using to properly route the request. * * @return The HTTP port WireMock is using. */ protected abstract int getWireMockPort(); @Host("http: @ServiceInterface(name = "Service1") private interface Service1 { @Get("bytes/100") @ExpectedResponses({200}) byte[] getByteArray(); @Get("bytes/100") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(); @Get("bytes/100") Mono<byte[]> getByteArrayAsyncWithNoExpectedResponses(); } @Test public void syncRequestWithByteArrayReturnType() { final byte[] result = createService(Service1.class).getByteArray(); assertNotNull(result); assertEquals(100, result.length); } @Test public void asyncRequestWithByteArrayReturnType() { StepVerifier.create(createService(Service1.class).getByteArrayAsync()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void getByteArrayAsyncWithNoExpectedResponses() { StepVerifier.create(createService(Service1.class).getByteArrayAsyncWithNoExpectedResponses()) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service2") private interface Service2 { @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) byte[] getByteArray(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); @Get("bytes/{numberOfBytes}") @ExpectedResponses({200}) Mono<byte[]> getByteArrayAsync(@HostParam("hostName") String host, @PathParam("numberOfBytes") int numberOfBytes); } @Test public void syncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 100); assertNotNull(result); assertEquals(result.length, 100); } @Test public void asyncRequestWithByteArrayReturnTypeAndParameterizedHostAndPath() { StepVerifier.create(createService(Service2.class).getByteArrayAsync("localhost", 100)) .assertNext(bytes -> assertEquals(100, bytes.length)) .verifyComplete(); } @Test public void syncRequestWithEmptyByteArrayReturnTypeAndParameterizedHostAndPath() { final byte[] result = createService(Service2.class).getByteArray("localhost", 0); assertNull(result); } @Host("http: @ServiceInterface(name = "Service3") private interface Service3 { @Get("bytes/100") @ExpectedResponses({200}) void getNothing(); @Get("bytes/100") @ExpectedResponses({200}) Mono<Void> getNothingAsync(); } @Test public void syncGetRequestWithNoReturn() { assertDoesNotThrow(() -> createService(Service3.class).getNothing()); } @Test public void asyncGetRequestWithNoReturn() { StepVerifier.create(createService(Service3.class).getNothingAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service5") private interface Service5 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(); @Get("anything/with+plus") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPlus(); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithPathParam(@PathParam("path") String pathParam); @Get("anything/{path}") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncodedPathParam(@PathParam(value = "path", encoded = true) String pathParam); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(); } @Test public void syncGetRequestWithAnything() { final HttpBinJSON json = createService(Service5.class).getAnything(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); } @Test public void syncGetRequestWithAnythingWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPlus(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+plus", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithSpace() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with path param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParam() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("withpathparam"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/withpathparam", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPercent20() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with%20path%20param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with path param", json.url()); } @Test public void syncGetRequestWithAnythingWithEncodedPathParamWithPlus() { final HttpBinJSON json = createService(Service5.class).getAnythingWithEncodedPathParam("with+path+param"); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything/with+path+param", json.url()); } @Test public void asyncGetRequestWithAnything() { StepVerifier.create(createService(Service5.class).getAnythingAsync()) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service6") private interface Service6 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@QueryParam("a") String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnythingWithEncoded(@QueryParam(value = "a", encoded = true) String a, @QueryParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@QueryParam("a") String a, @QueryParam("b") int b); } @Test public void syncGetRequestWithQueryParametersAndAnything() { final HttpBinJSON json = createService(Service6.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnything("A%20Z", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=A%2520Z&b=15", json.url()); } @Test public void syncGetRequestWithQueryParametersAndAnythingWithEncodedWithPercent20() { final HttpBinJSON json = createService(Service6.class).getAnythingWithEncoded("x%20y", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?a=x y&b=15", json.url()); } @Test public void asyncGetRequestWithQueryParametersAndAnything() { StepVerifier.create(createService(Service6.class).getAnythingAsync("A", 15)) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/anything?a=A&b=15", json.url())) .verifyComplete(); } @Test public void syncGetRequestWithNullQueryParameter() { final HttpBinJSON json = createService(Service6.class).getAnything(null, 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything?b=15", json.url()); } @Host("http: @ServiceInterface(name = "Service7") private interface Service7 { @Get("anything") @ExpectedResponses({200}) HttpBinJSON getAnything(@HeaderParam("a") String a, @HeaderParam("b") int b); @Get("anything") @ExpectedResponses({200}) Mono<HttpBinJSON> getAnythingAsync(@HeaderParam("a") String a, @HeaderParam("b") int b); } @Test public void syncGetRequestWithHeaderParametersAndAnythingReturn() { final HttpBinJSON json = createService(Service7.class).getAnything("A", 15); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Test public void asyncGetRequestWithHeaderParametersAndAnything() { StepVerifier.create(createService(Service7.class).getAnythingAsync("A", 15)) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("A", headers.getValue("A")); assertArrayEquals(new String[]{"A"}, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); }) .verifyComplete(); } @Test public void syncGetRequestWithNullHeader() { final HttpBinJSON json = createService(Service7.class).getAnything(null, 15); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertNull(headers.getValue("A")); assertArrayEquals(null, headers.getValues("A")); assertEquals("15", headers.getValue("B")); assertArrayEquals(new String[]{"15"}, headers.getValues("B")); } @Host("http: @ServiceInterface(name = "Service8") private interface Service8 { @Post("post") @ExpectedResponses({200}) HttpBinJSON post(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); @Post("post") @ExpectedResponses({200}) Mono<HttpBinJSON> postAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String postBody); } @Test public void syncPostRequestWithStringBody() { final HttpBinJSON json = createService(Service8.class).post("I'm a post body!"); assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); } @Test public void asyncPostRequestWithStringBody() { StepVerifier.create(createService(Service8.class).postAsync("I'm a post body!")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("I'm a post body!", json.data()); }) .verifyComplete(); } @Test public void syncPostRequestWithNullBody() { final HttpBinJSON result = createService(Service8.class).post(null); assertEquals("", result.data()); } @Host("http: @ServiceInterface(name = "Service9") private interface Service9 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) Flux<ByteBuffer> body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putAsyncBodyAndContentLength( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) BinaryData body, @HeaderParam("Content-Length") long contentLength); @Put("put") @ExpectedResponses({201}) HttpBinJSON putWithUnexpectedResponse(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) Mono<HttpBinJSON> putWithUnexpectedResponseAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) HttpBinJSON putWithUnexpectedResponseAndDeterminedExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {200}, value = MyRestException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndDeterminedExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = HttpResponseException.class) @UnexpectedResponseExceptionType(MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) HttpBinJSON putWithUnexpectedResponseAndNoFallthroughExceptionType( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); @Put("put") @ExpectedResponses({201}) @UnexpectedResponseExceptionType(code = {400}, value = MyRestException.class) Mono<HttpBinJSON> putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String putBody); } @Test public void syncPutRequestWithIntBody() { final HttpBinJSON json = createService(Service9.class).put(42); assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); } @Test public void asyncPutRequestWithIntBody() { StepVerifier.create(createService(Service9.class).putAsync(42)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("42", json.data()); }).verifyComplete(); } @Test public void syncPutRequestWithBodyAndEqualContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); final HttpBinJSON json = createService(Service9.class).putBodyAndContentLength(body, 4L); assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); } @Test public void syncPutRequestWithBodyLessThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 5L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("less than")); } @Test public void syncPutRequestWithBodyMoreThanContentLength() { ByteBuffer body = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); Exception unexpectedLengthException = assertThrows(Exception.class, () -> { createService(Service9.class).putBodyAndContentLength(body, 3L); body.clear(); }); assertTrue(unexpectedLengthException.getMessage().contains("more than")); } @Test public void asyncPutRequestWithBodyAndEqualContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 4L)) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBodyAndLessThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 5L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBodyAndMoreThanContentLength() { Flux<ByteBuffer> body = Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8))); StepVerifier.create(createService(Service9.class).putAsyncBodyAndContentLength(body, 3L)) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndEqualContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 4L))) .assertNext(json -> { assertEquals("test", json.data()); assertEquals(ContentType.APPLICATION_OCTET_STREAM, json.getHeaderValue("Content-Type")); assertEquals("4", json.getHeaderValue("Content-Length")); }).verifyComplete(); } @Test public void asyncPutRequestWithBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndLessThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 5L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("less than")); }); } @Test public void asyncPutRequestWithBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = BinaryData.fromFlux( Flux.just(ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } /** * LengthValidatingInputStream in rest proxy relies on reader * reaching EOF. This test specifically targets InputStream to assert this behavior. */ @Test public void asyncPutRequestWithStreamBinaryDataBodyAndMoreThanContentLength() { Mono<BinaryData> bodyMono = Mono.just(BinaryData.fromStream( new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)))); StepVerifier.create( bodyMono.flatMap(body -> createService(Service9.class).putAsyncBodyAndContentLength(body, 3L))) .verifyErrorSatisfies(exception -> { assertTrue(exception instanceof UnexpectedLengthException || (exception.getSuppressed().length > 0 && exception.getSuppressed()[0] instanceof UnexpectedLengthException)); assertTrue(exception.getMessage().contains("more than")); }); } @Test public void syncPutRequestWithUnexpectedResponse() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponse("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponse() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException); HttpResponseException exception = (HttpResponseException) throwable; assertNotNull(exception.getValue()); assertTrue(exception.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) exception.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Test public void syncPutRequestWithUnexpectedResponseAndExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException myRestException = (MyRestException) throwable; assertNotNull(myRestException.getValue()); assertEquals("I'm the body!", myRestException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndDeterminedExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndDeterminedExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { MyRestException e = assertThrows(MyRestException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertEquals("I'm the body!", e.getValue().data()); } @Test public void asyncPutRequestWithUnexpectedResponseAndFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof MyRestException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); MyRestException restException = (MyRestException) throwable; assertNotNull(restException.getValue()); assertEquals("I'm the body!", restException.getValue().data()); }); } @Test public void syncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionType("I'm the body!")); assertNotNull(e.getValue()); assertTrue(e.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) e.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); } @Test public void asyncPutRequestWithUnexpectedResponseAndNoFallthroughExceptionType() { StepVerifier.create(createService(Service9.class).putWithUnexpectedResponseAndNoFallthroughExceptionTypeAsync("I'm the body!")) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof HttpResponseException, "Expected MyRestException would be thrown. Instead got " + throwable.getClass().getSimpleName()); HttpResponseException responseException = (HttpResponseException) throwable; assertNotNull(responseException.getValue()); assertTrue(responseException.getValue() instanceof LinkedHashMap); @SuppressWarnings("unchecked") final LinkedHashMap<String, String> expectedBody = (LinkedHashMap<String, String>) responseException.getValue(); assertEquals("I'm the body!", expectedBody.get("data")); }); } @Host("http: @ServiceInterface(name = "Service10") private interface Service10 { @Head("anything") @ExpectedResponses({200}) Response<Void> head(); @Head("anything") @ExpectedResponses({200}) boolean headBoolean(); @Head("anything") @ExpectedResponses({200}) void voidHead(); @Head("anything") @ExpectedResponses({200}) Mono<Response<Void>> headAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Boolean> headBooleanAsync(); @Head("anything") @ExpectedResponses({200}) Mono<Void> completableHeadAsync(); } @Test public void syncHeadRequest() { final Void body = createService(Service10.class).head().getValue(); assertNull(body); } @Test public void syncHeadBooleanRequest() { final boolean result = createService(Service10.class).headBoolean(); assertTrue(result); } @Test public void syncVoidHeadRequest() { createService(Service10.class) .voidHead(); } @Test public void asyncHeadRequest() { StepVerifier.create(createService(Service10.class).headAsync()) .assertNext(response -> assertNull(response.getValue())) .verifyComplete(); } @Test public void asyncHeadBooleanRequest() { StepVerifier.create(createService(Service10.class).headBooleanAsync()) .assertNext(Assertions::assertTrue) .verifyComplete(); } @Test public void asyncCompletableHeadRequest() { StepVerifier.create(createService(Service10.class).completableHeadAsync()) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service11") private interface Service11 { @Delete("delete") @ExpectedResponses({200}) HttpBinJSON delete(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); @Delete("delete") @ExpectedResponses({200}) Mono<HttpBinJSON> deleteAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) boolean bodyBoolean); } @Test public void syncDeleteRequest() { final HttpBinJSON json = createService(Service11.class).delete(false); assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); } @Test public void asyncDeleteRequest() { StepVerifier.create(createService(Service11.class).deleteAsync(false)) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("false", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service12") private interface Service12 { @Patch("patch") @ExpectedResponses({200}) HttpBinJSON patch(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); @Patch("patch") @ExpectedResponses({200}) Mono<HttpBinJSON> patchAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String bodyString); } @Test public void syncPatchRequest() { final HttpBinJSON json = createService(Service12.class).patch("body-contents"); assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); } @Test public void asyncPatchRequest() { StepVerifier.create(createService(Service12.class).patchAsync("body-contents")) .assertNext(json -> { assertEquals(String.class, json.data().getClass()); assertEquals("body-contents", json.data()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service13") private interface Service13 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue", "MyOtherHeader:My,Header,Value"}) Mono<HttpBinJSON> getAsync(); } @Test public void syncHeadersRequest() { final HttpBinJSON json = createService(Service13.class).get(); assertNotNull(json); assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); assertEquals("My,Header,Value", headers.getValue("MyOtherHeader")); assertArrayEquals(new String[]{"My", "Header", "Value"}, headers.getValues("MyOtherHeader")); } @Test public void asyncHeadersRequest() { StepVerifier.create(createService(Service13.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); assertArrayEquals(new String[]{"MyHeaderValue"}, headers.getValues("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service14") private interface Service14 { @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) HttpBinJSON get(); @Get("anything") @ExpectedResponses({200}) @Headers({"MyHeader:MyHeaderValue"}) Mono<HttpBinJSON> getAsync(); } @Test public void asyncHttpsHeadersRequest() { StepVerifier.create(createService(Service14.class).getAsync()) .assertNext(json -> { assertMatchWithHttpOrHttps("localhost/anything", json.url()); assertNotNull(json.headers()); final HttpHeaders headers = new HttpHeaders().setAll(json.headers()); assertEquals("MyHeaderValue", headers.getValue("MyHeader")); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service16") private interface Service16 { @Put("put") @ExpectedResponses({200}) HttpBinJSON putByteArray(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); @Put("put") @ExpectedResponses({200}) Mono<HttpBinJSON> putByteArrayAsync(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] bytes); } @Test public void service16Put() { final Service16 service16 = createService(Service16.class); final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; final HttpBinJSON httpBinJSON = service16.putByteArray(expectedBytes); assertTrue(httpBinJSON.data() instanceof String); final String base64String = (String) httpBinJSON.data(); final byte[] actualBytes = base64String.getBytes(); assertArrayEquals(expectedBytes, actualBytes); } @Test public void service16PutAsync() { final byte[] expectedBytes = new byte[]{1, 2, 3, 4}; StepVerifier.create(createService(Service16.class).putByteArrayAsync(expectedBytes)) .assertNext(json -> { assertTrue(json.data() instanceof String); assertArrayEquals(expectedBytes, ((String) json.data()).getBytes()); }).verifyComplete(); } @Host("http: @ServiceInterface(name = "Service17") private interface Service17 { @Get("get") @ExpectedResponses({200}) HttpBinJSON get(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); @Get("get") @ExpectedResponses({200}) Mono<HttpBinJSON> getAsync(@HostParam("hostPart1") String hostPart1, @HostParam("hostPart2") String hostPart2); } @Test public void syncRequestWithMultipleHostParams() { final HttpBinJSON result = createService(Service17.class).get("local", "host"); assertNotNull(result); assertMatchWithHttpOrHttps("localhost/get", result.url()); } @Test public void asyncRequestWithMultipleHostParams() { StepVerifier.create(createService(Service17.class).getAsync("local", "host")) .assertNext(json -> assertMatchWithHttpOrHttps("localhost/get", json.url())) .verifyComplete(); } @Host("http: @ServiceInterface(name = "Service18") private interface Service18 { @Get("status/200") void getStatus200(); @Get("status/200") @ExpectedResponses({200}) void getStatus200WithExpectedResponse200(); @Get("status/300") void getStatus300(); @Get("status/300") @ExpectedResponses({300}) void getStatus300WithExpectedResponse300(); @Get("status/400") void getStatus400(); @Get("status/400") @ExpectedResponses({400}) void getStatus400WithExpectedResponse400(); @Get("status/500") void getStatus500(); @Get("status/500") @ExpectedResponses({500}) void getStatus500WithExpectedResponse500(); } @Test public void service18GetStatus200() { createService(Service18.class).getStatus200(); } @Test public void service18GetStatus200WithExpectedResponse200() { assertDoesNotThrow(() -> createService(Service18.class).getStatus200WithExpectedResponse200()); } @Test public void service18GetStatus300() { createService(Service18.class).getStatus300(); } @Test public void service18GetStatus300WithExpectedResponse300() { assertDoesNotThrow(() -> createService(Service18.class).getStatus300WithExpectedResponse300()); } @Test public void service18GetStatus400() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus400()); } @Test public void service18GetStatus400WithExpectedResponse400() { assertDoesNotThrow(() -> createService(Service18.class).getStatus400WithExpectedResponse400()); } @Test public void service18GetStatus500() { assertThrows(HttpResponseException.class, () -> createService(Service18.class).getStatus500()); } @Test public void service18GetStatus500WithExpectedResponse500() { assertDoesNotThrow(() -> createService(Service18.class).getStatus500WithExpectedResponse500()); } @Host("http: @ServiceInterface(name = "Service19") private interface Service19 { @Put("put") HttpBinJSON putWithNoContentTypeAndStringBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithNoContentTypeAndByteArrayBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithHeaderApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") @Headers({"Content-Type: application/json"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") @Headers({"Content-Type: application/json; charset=utf-8"}) HttpBinJSON putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") @Headers({"Content-Type: application/octet-stream"}) HttpBinJSON putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_JSON) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody( @BodyParam(ContentType.APPLICATION_JSON + "; charset=utf-8") String body); @Put("put") HttpBinJSON putWithBodyParamApplicationJsonContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_JSON) byte[] body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndStringBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") HttpBinJSON putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) byte[] body); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndStringBody("hello"); assertEquals("hello", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class).putWithNoContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithNoContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithNoContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("soups and stuff", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithHeaderApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithHeaderApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody(""); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndCharsetAndStringBody("soups and stuff"); assertEquals("\"soups and stuff\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[0]); assertEquals("\"\"", result.data()); } @Test public void service19PutWithBodyParamApplicationJsonContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationJsonContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals("\"AAECAwQ=\"", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody(""); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndStringBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndStringBody("penguins"); assertEquals("penguins", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNullBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(null); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[0]); assertEquals("", result.data()); } @Test public void service19PutWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBodyWithNonEmptyBody() { final HttpBinJSON result = createService(Service19.class) .putWithBodyParamApplicationOctetStreamContentTypeAndByteArrayBody(new byte[]{0, 1, 2, 3, 4}); assertEquals(new String(new byte[]{0, 1, 2, 3, 4}), result.data()); } @Host("http: @ServiceInterface(name = "Service20") private interface Service20 { @Get("bytes/100") ResponseBase<HttpBinHeaders, Void> getBytes100OnlyHeaders(); @Get("bytes/100") ResponseBase<HttpHeaders, Void> getBytes100OnlyRawHeaders(); @Get("bytes/100") ResponseBase<HttpBinHeaders, byte[]> getBytes100BodyAndHeaders(); @Put("put") ResponseBase<HttpBinHeaders, Void> putOnlyHeaders(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Put("put") ResponseBase<HttpBinHeaders, HttpBinJSON> putBodyAndHeaders( @BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); @Get("bytes/100") ResponseBase<Void, Void> getBytesOnlyStatus(); @Get("bytes/100") Response<Void> getVoidResponse(); @Put("put") Response<HttpBinJSON> putBody(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) String body); } @Test public void service20GetBytes100OnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).getBytes100OnlyHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytes100BodyAndHeaders() { final ResponseBase<HttpBinHeaders, byte[]> response = createService(Service20.class).getBytes100BodyAndHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); final byte[] body = response.getValue(); assertNotNull(body); assertEquals(100, body.length); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetBytesOnlyStatus() { final Response<Void> response = createService(Service20.class).getBytesOnlyStatus(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetBytesOnlyHeaders() { final Response<Void> response = createService(Service20.class).getBytes100OnlyRawHeaders(); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertNotNull(response.getHeaders()); assertNotEquals(0, response.getHeaders().getSize()); } @Test public void service20PutOnlyHeaders() { final ResponseBase<HttpBinHeaders, Void> response = createService(Service20.class).putOnlyHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20PutBodyAndHeaders() { final ResponseBase<HttpBinHeaders, HttpBinJSON> response = createService(Service20.class).putBodyAndHeaders("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpBinHeaders headers = response.getDeserializedHeaders(); assertNotNull(headers); assertTrue(headers.accessControlAllowCredentials()); assertNotNull(headers.date()); assertNotEquals(0, (Object) headers.xProcessedTime()); } @Test public void service20GetVoidResponse() { final Response<Void> response = createService(Service20.class).getVoidResponse(); assertNotNull(response); assertEquals(200, response.getStatusCode()); } @Test public void service20GetResponseBody() { final Response<HttpBinJSON> response = createService(Service20.class).putBody("body string"); assertNotNull(response); assertEquals(200, response.getStatusCode()); final HttpBinJSON body = response.getValue(); assertNotNull(body); assertMatchWithHttpOrHttps("localhost/put", body.url()); assertEquals("body string", body.data()); final HttpHeaders headers = response.getHeaders(); assertNotNull(headers); } @Host("http: @ServiceInterface(name = "UnexpectedOKService") interface UnexpectedOKService { @Get("/bytes/1024") @ExpectedResponses({400}) StreamResponse getBytes(); } @Test public void unexpectedHTTPOK() { HttpResponseException e = assertThrows(HttpResponseException.class, () -> createService(UnexpectedOKService.class).getBytes()); assertEquals("Status code 200, (1024-byte body)", e.getMessage()); } @Host("https: @ServiceInterface(name = "Service21") private interface Service21 { @Get("http: @ExpectedResponses({200}) byte[] getBytes100(); } @Test public void service21GetBytes100() { final byte[] bytes = createService(Service21.class).getBytes100(); assertNotNull(bytes); assertEquals(100, bytes.length); } @Host("http: @ServiceInterface(name = "DownloadService") interface DownloadService { @Get("/bytes/30720") StreamResponse getBytes(Context context); @Get("/bytes/30720") Mono<StreamResponse> getBytesAsync(Context context); @Get("/bytes/30720") Flux<ByteBuffer> getBytesFlux(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void simpleDownloadTestAsync(Context context) { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> response.getValue().map(ByteBuffer::remaining) .reduce(0, Integer::sum) .doFinally(ignore -> response.close()))) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(response -> Mono.zip(MessageDigestUtils.md5(response.getValue()), Mono.just(response.getHeaders().getValue("ETag"))) .doFinally(ignore -> response.close()))) .assertNext(hashTuple -> assertEquals(hashTuple.getT2(), hashTuple.getT1())) .verifyComplete(); } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBody(Context context) throws IOException { try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); streamResponse.transferValueTo(Channels.newChannel(bos)); assertEquals(streamResponse.getHeaders().getValue("ETag"), MessageDigestUtils.md5(bos.toByteArray())); } Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); try (StreamResponse streamResponse = createService(DownloadService.class).getBytes(context)) { StepVerifier.create(Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).then(Mono.fromCallable(() -> MessageDigestUtils.md5(Files.readAllBytes(tempFile))))) .assertNext(hash -> assertEquals(streamResponse.getHeaders().getValue("ETag"), hash)) .verifyComplete(); } } @ParameterizedTest @MethodSource("downloadTestArgumentProvider") public void streamResponseCanTransferBodyAsync(Context context) throws IOException { StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .publishOn(Schedulers.boundedElastic()) .map(streamResponse -> { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { streamResponse.transferValueTo(Channels.newChannel(bos)); } catch (IOException e) { throw Exceptions.propagate(e); } finally { streamResponse.close(); } return Tuples.of(streamResponse.getHeaders().getValue("Etag"), MessageDigestUtils.md5(bos.toByteArray())); })) .assertNext(hashTuple -> assertEquals(hashTuple.getT1(), hashTuple.getT2())) .verifyComplete(); Path tempFile = Files.createTempFile("streamResponseCanTransferBody", null); tempFile.toFile().deleteOnExit(); StepVerifier.create(createService(DownloadService.class).getBytesAsync(context) .flatMap(streamResponse -> Mono.using( () -> IOUtils.toAsynchronousByteChannel(AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0), streamResponse::transferValueToAsync, channel -> { try { channel.close(); } catch (IOException e) { throw Exceptions.propagate(e); } }).doFinally(ignored -> streamResponse.close()) .then(Mono.just(streamResponse.getHeaders().getValue("ETag"))))) .assertNext(hash -> { try { assertEquals(hash, MessageDigestUtils.md5(Files.readAllBytes(tempFile))); } catch (IOException e) { Exceptions.propagate(e); } }) .verifyComplete(); } public static Stream<Arguments> downloadTestArgumentProvider() { return Stream.of( Arguments.of(Named.named("default", Context.NONE)), Arguments.of(Named.named("sync proxy enabled", Context.NONE .addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true)))); } @Test public void rawFluxDownloadTest() { StepVerifier.create(createService(DownloadService.class).getBytesFlux() .map(ByteBuffer::remaining).reduce(0, Integer::sum)) .assertNext(count -> assertEquals(30720, count)) .verifyComplete(); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface FluxUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") Flux<ByteBuffer> content, @HeaderParam("Content-Length") long contentLength); } @Test public void fluxUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); Flux<ByteBuffer> stream = FluxUtil.readFile(AsynchronousFileChannel.open(filePath)); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(FluxUploadService.class, httpPipeline).put(stream, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Test public void segmentUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(filePath, StandardOpenOption.READ); Response<HttpBinJSON> response = createService(FluxUploadService.class) .put(FluxUtil.readFile(fileChannel, 4, 15), 15); assertEquals("quick brown fox", response.getValue().data()); } @Host("http: @ServiceInterface(name = "FluxUploadService") interface BinaryDataUploadService { @Put("/put") Response<HttpBinJSON> put(@BodyParam("text/plain") BinaryData content, @HeaderParam("Content-Length") long contentLength); } @Test public void binaryDataUploadTest() throws Exception { Path filePath = Paths.get(getClass().getClassLoader().getResource("upload.txt").toURI()); BinaryData data = BinaryData.fromFile(filePath); final HttpClient httpClient = createHttpClient(); final HttpPipeline httpPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new PortPolicy(getWireMockPort(), true), new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))) .build(); Response<HttpBinJSON> response = RestProxy .create(BinaryDataUploadService.class, httpPipeline).put(data, Files.size(filePath)); assertEquals("The quick brown fox jumps over the lazy dog", response.getValue().data()); } @Host("{url}") @ServiceInterface(name = "Service22") interface Service22 { @Get("/") byte[] getBytes(@HostParam("url") String url); } @Test public void service22GetBytes() { final byte[] bytes = createService(Service22.class).getBytes("http: assertNotNull(bytes); assertEquals(27, bytes.length); } @Host("http: @ServiceInterface(name = "Service23") interface Service23 { @Get("bytes/28") byte[] getBytes(); } @Test public void service23GetBytes() { final byte[] bytes = createService(Service23.class).getBytes(); assertNotNull(bytes); assertEquals(28, bytes.length); } @Host("http: @ServiceInterface(name = "Service24") interface Service24 { @Put("put") HttpBinJSON put(@HeaderParam("ABC") Map<String, String> headerCollection); } @Test public void service24Put() { final Map<String, String> headerCollection = new HashMap<>(); headerCollection.put("DEF", "GHIJ"); headerCollection.put("123", "45"); final HttpBinJSON result = createService(Service24.class) .put(headerCollection); assertNotNull(result.headers()); final HttpHeaders resultHeaders = new HttpHeaders().setAll(result.headers()); assertEquals("GHIJ", resultHeaders.getValue("ABCDEF")); assertEquals("45", resultHeaders.getValue("ABC123")); } @Host("http: @ServiceInterface(name = "Service26") interface Service26 { @Post("post") HttpBinFormDataJSON postForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam("custemail") String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); @Post("post") HttpBinFormDataJSON postEncodedForm(@FormParam("custname") String name, @FormParam("custtel") String telephone, @FormParam(value = "custemail", encoded = true) String email, @FormParam("size") PizzaSize size, @FormParam("toppings") List<String> toppings); } @Test public void postUrlForm() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo%40bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Test public void postUrlFormEncoded() { Service26 service = createService(Service26.class); HttpBinFormDataJSON response = service.postEncodedForm("Foo", "123", "foo@bar.com", PizzaSize.LARGE, Arrays.asList("Bacon", "Onion")); assertNotNull(response); assertNotNull(response.form()); assertEquals("Foo", response.form().customerName()); assertEquals("123", response.form().customerTelephone()); assertEquals("foo@bar.com", response.form().customerEmail()); assertEquals(PizzaSize.LARGE, response.form().pizzaSize()); assertEquals(2, response.form().toppings().size()); assertEquals("Bacon", response.form().toppings().get(0)); assertEquals("Onion", response.form().toppings().get(1)); } @Host("http: @ServiceInterface(name = "Service27") interface Service27 { @Put("put") @ExpectedResponses({200}) HttpBinJSON put(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions requestOptions); @Put("put") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(MyRestException.class) HttpBinJSON putBodyAndContentLength(@BodyParam(ContentType.APPLICATION_OCTET_STREAM) ByteBuffer body, @HeaderParam("Content-Length") long contentLength, RequestOptions requestOptions); } @Test public void requestOptionsChangesBody() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("24"))); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("24", response.data()); } @Test public void requestOptionsChangesBodyAndContentLength() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().setBody(BinaryData.fromString("4242")) .setHeader("Content-Length", "4")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("4242", response.data()); assertEquals("4", response.getHeaderValue("Content-Length")); } @Test public void requestOptionsAddAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue", response.getHeaderValue("randomHeader")); } @Test public void requestOptionsSetsAHeader() { Service27 service = createService(Service27.class); HttpBinJSON response = service.put(42, new RequestOptions().addHeader("randomHeader", "randomValue") .setHeader("randomHeader", "randomValue2")); assertNotNull(response); assertNotNull(response.data()); assertTrue(response.data() instanceof String); assertEquals("42", response.data()); assertEquals("randomValue2", response.getHeaderValue("randomHeader")); } protected <T> T createService(Class<T> serviceClass) { final HttpClient httpClient = createHttpClient(); return createService(serviceClass, httpClient); } protected <T> T createService(Class<T> serviceClass, HttpClient httpClient) { final HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(new PortPolicy(getWireMockPort(), true)) .httpClient(httpClient) .build(); return RestProxy.create(serviceClass, httpPipeline); } private static void assertMatchWithHttpOrHttps(String url1, String url2) { final String s1 = "http: if (s1.equalsIgnoreCase(url2)) { return; } final String s2 = "https: if (s2.equalsIgnoreCase(url2)) { return; } fail("'" + url2 + "' does not match with '" + s1 + "' or '" + s2 + "'."); } }
May want to use `Mono.fromSupplier` as this'll eagerly create the authorization header
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); return Mono.just(credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents)) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process()); }
return Mono.just(credentials
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return Mono.defer(() -> Mono.just(credentials.getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData())) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process())); }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } private ByteBuffer getEmptyBuffer() { return ByteBuffer.allocate(0); } }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData()); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } }
Not this PR but could we merge this into a single operation and remove the `.last()`
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); return Mono.just(credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents)) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process()); }
.getAuthorizationHeaders(
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return Mono.defer(() -> Mono.just(credentials.getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData())) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process())); }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } private ByteBuffer getEmptyBuffer() { return ByteBuffer.allocate(0); } }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData()); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } }
for future. would it make sense for getAuthorizationHeaders to take BinaryData?
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); return Mono.just(credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents)) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process()); }
contents))
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return Mono.defer(() -> Mono.just(credentials.getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData())) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process())); }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } private ByteBuffer getEmptyBuffer() { return ByteBuffer.allocate(0); } }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData()); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } }
+1
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); return Mono.just(credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents)) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process()); }
return Mono.just(credentials
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return Mono.defer(() -> Mono.just(credentials.getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData())) .flatMapMany(headers -> Flux.fromIterable(headers.entrySet())) .map(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())) .last() .flatMap(request -> next.process())); }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { final ByteBuffer contents = context.getHttpRequest().getBodyAsBinaryData() == null ? getEmptyBuffer() : context.getHttpRequest().getBodyAsBinaryData().toByteBuffer(); Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), contents); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } private ByteBuffer getEmptyBuffer() { return ByteBuffer.allocate(0); } }
class ConfigurationCredentialsPolicy implements HttpPipelinePolicy { private final ConfigurationClientCredentials credentials; /** * Creates an instance that is able to apply a {@link ConfigurationClientCredentials} credential to a request in the * pipeline. * * @param credentials the credential information to authenticate to Azure App Configuration service * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationCredentialsPolicy(ConfigurationClientCredentials credentials) { Objects.requireNonNull(credentials, "'credential' can not be a null value."); this.credentials = credentials; } /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link Mono} representing the HTTP response that will arrive asynchronously. */ @Override /** * Adds the required headers to authenticate a request to Azure App Configuration service. * * @param context The request context * @param next The next HTTP pipeline policy to process the {@code context's} request after this policy * completes. * @return A {@link HttpResponse} that will arrive synchronously. */ @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { Map<String, String> headers = credentials .getAuthorizationHeaders( context.getHttpRequest().getUrl(), context.getHttpRequest().getHttpMethod().toString(), context.getHttpRequest().getBodyAsBinaryData()); headers.entrySet() .stream() .forEach(header -> context.getHttpRequest().setHeader(header.getKey(), header.getValue())); return next.processSync(); } }
If this happens, we should fail the test. So, instead of catching this exception, we can just declare this test method to throw that'll cause test failure. (do the same in other places where exceptions are caught).
protected void beforeTest() { try { ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder() .certificateEndpoint( Configuration.getGlobalConfiguration().get("IDENTITYSERVICEURI", "https: .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerCertificateClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerCertificateClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder .buildClient(); String ledgerId = Configuration.getGlobalConfiguration().get("LEDGERID", "emily-java-sdk-tests"); confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder() .ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGERURI", "https: .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder.credential(new AzureCliCredentialBuilder().build()); } } catch (Exception ex) { System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex); } String ledgerId = Configuration.getGlobalConfiguration().get("LEDGERID", "emily-java-sdk-tests"); Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient .getLedgerIdentityWithResponse(ledgerId, null); BinaryData identityResponse = ledgerIdentityWithResponse.getValue(); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = null; try { jsonNode = mapper.readTree(identityResponse.toBytes()); } catch (IOException ex) { System.out.println("Caught exception " + ex); } String ledgerTslCertificate = jsonNode.get("ledgerTlsCertificate").asText(); reactor.netty.http.client.HttpClient reactorClient = null; try { final SslContext sslContext = SslContextBuilder.forClient().trustManager(new ByteArrayInputStream(ledgerTslCertificate.getBytes(StandardCharsets.UTF_8))).build(); reactorClient = reactor.netty.http.client.HttpClient.create(); reactorClient.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException ex) { System.out.println("Caught exception " + ex); } HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build(); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .httpClient(httpClient) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder .credential(new DefaultAzureCredentialBuilder().build()) .httpClient(httpClient); } confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient(); }
System.out.println("Caught exception " + ex);
protected void beforeTest() { try { ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder() .certificateEndpoint("https: .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerCertificateClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerCertificateClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder .buildClient(); String ledgerId = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-test"); confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder() .ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https: .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder.credential(new AzureCliCredentialBuilder().build()); } } catch (Exception ex) { System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex); } String ledgerId = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests"); Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient .getLedgerIdentityWithResponse(ledgerId, null); BinaryData identityResponse = ledgerIdentityWithResponse.getValue(); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = null; try { jsonNode = mapper.readTree(identityResponse.toBytes()); } catch (IOException ex) { System.out.println("Caught exception " + ex); Assertions.assertTrue(false); } String ledgerTslCertificate = jsonNode.get("ledgerTlsCertificate").asText(); reactor.netty.http.client.HttpClient reactorClient = null; try { final SslContext sslContext = SslContextBuilder.forClient().trustManager(new ByteArrayInputStream(ledgerTslCertificate.getBytes(StandardCharsets.UTF_8))).build(); reactorClient = reactor.netty.http.client.HttpClient.create(); reactorClient.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException ex) { System.out.println("Caught exception " + ex); Assertions.assertTrue(false); } HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build(); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .httpClient(httpClient) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder .credential(new DefaultAzureCredentialBuilder().build()) .httpClient(httpClient); } confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient(); }
class ConfidentialLedgerClientTestBase extends TestBase { protected ConfidentialLedgerClient confidentialLedgerClient; protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder; protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient; @Override }
class ConfidentialLedgerClientTestBase extends TestBase { protected ConfidentialLedgerClient confidentialLedgerClient; protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder; protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient; @Override }
We should remove the whole `catch` block and let the exception bubble up.
protected void beforeTest() { try { ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder() .certificateEndpoint( Configuration.getGlobalConfiguration().get("IDENTITYSERVICEURI", "https: .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerCertificateClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerCertificateClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder .buildClient(); String ledgerId = Configuration.getGlobalConfiguration().get("LEDGERID", "emily-java-sdk-tests"); confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder() .ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGERURI", "https: .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder.credential(new AzureCliCredentialBuilder().build()); } } catch (Exception ex) { System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex); } String ledgerId = Configuration.getGlobalConfiguration().get("LEDGERID", "emily-java-sdk-tests"); Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient .getLedgerIdentityWithResponse(ledgerId, null); BinaryData identityResponse = ledgerIdentityWithResponse.getValue(); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = null; try { jsonNode = mapper.readTree(identityResponse.toBytes()); } catch (IOException ex) { System.out.println("Caught exception " + ex); } String ledgerTslCertificate = jsonNode.get("ledgerTlsCertificate").asText(); reactor.netty.http.client.HttpClient reactorClient = null; try { final SslContext sslContext = SslContextBuilder.forClient().trustManager(new ByteArrayInputStream(ledgerTslCertificate.getBytes(StandardCharsets.UTF_8))).build(); reactorClient = reactor.netty.http.client.HttpClient.create(); reactorClient.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException ex) { System.out.println("Caught exception " + ex); } HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build(); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .httpClient(httpClient) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder .credential(new DefaultAzureCredentialBuilder().build()) .httpClient(httpClient); } confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient(); }
System.out.println("Caught exception " + ex);
protected void beforeTest() { try { ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder() .certificateEndpoint("https: .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerCertificateClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerCertificateClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder .buildClient(); String ledgerId = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-test"); confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder() .ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https: .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder.credential(new AzureCliCredentialBuilder().build()); } } catch (Exception ex) { System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex); } String ledgerId = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests"); Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient .getLedgerIdentityWithResponse(ledgerId, null); BinaryData identityResponse = ledgerIdentityWithResponse.getValue(); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = null; try { jsonNode = mapper.readTree(identityResponse.toBytes()); } catch (IOException ex) { System.out.println("Caught exception " + ex); Assertions.assertTrue(false); } String ledgerTslCertificate = jsonNode.get("ledgerTlsCertificate").asText(); reactor.netty.http.client.HttpClient reactorClient = null; try { final SslContext sslContext = SslContextBuilder.forClient().trustManager(new ByteArrayInputStream(ledgerTslCertificate.getBytes(StandardCharsets.UTF_8))).build(); reactorClient = reactor.netty.http.client.HttpClient.create(); reactorClient.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException ex) { System.out.println("Caught exception " + ex); Assertions.assertTrue(false); } HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build(); if (getTestMode() == TestMode.PLAYBACK) { confidentialLedgerClientBuilder .httpClient(interceptorManager.getPlaybackClient()) .credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX))); } else if (getTestMode() == TestMode.RECORD) { confidentialLedgerClientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .httpClient(httpClient) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { confidentialLedgerClientBuilder .credential(new DefaultAzureCredentialBuilder().build()) .httpClient(httpClient); } confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient(); }
class ConfidentialLedgerClientTestBase extends TestBase { protected ConfidentialLedgerClient confidentialLedgerClient; protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder; protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient; @Override }
class ConfidentialLedgerClientTestBase extends TestBase { protected ConfidentialLedgerClient confidentialLedgerClient; protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder; protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient; @Override }
Just curious, why is the new code better?
public Mono<Void> runAsync() { return Mono.fromSupplier(binaryDataSupplier) .flatMap(data -> service.setBinaryData(endpoint, id, data, length)); }
.flatMap(data -> service.setBinaryData(endpoint, id, data, length));
public Mono<Void> runAsync() { return Mono.fromSupplier(binaryDataSupplier) .flatMap(data -> service.setBinaryData(endpoint, id, data, length)); }
class BinaryDataSendTest extends RestProxyTestBase<CorePerfStressOptions> { private final long length; private final Supplier<BinaryData> binaryDataSupplier; public BinaryDataSendTest(CorePerfStressOptions options) { super(options); length = options.getSize(); binaryDataSupplier = createBinaryDataSupplier(options); } @Override public void run() { runAsync().block(); } @Override }
class BinaryDataSendTest extends RestProxyTestBase<CorePerfStressOptions> { private final long length; private final Supplier<BinaryData> binaryDataSupplier; public BinaryDataSendTest(CorePerfStressOptions options) { super(options); length = options.getSize(); binaryDataSupplier = createBinaryDataSupplier(options); } @Override public void run() { runAsync().block(); } @Override }
The `binaryDataSupplier` is supposed to supply fresh `BinaryData` for each `runAsync`. The old code is effectively doing that, but only because the caller uses `flatMap` - which is just luck rather than proper reactive stream. Wrapping the supplier in Mono makes it properly reactive, i.e. subscriber triggers binary data creation regardless of what caller of this is doing.
public Mono<Void> runAsync() { return Mono.fromSupplier(binaryDataSupplier) .flatMap(data -> service.setBinaryData(endpoint, id, data, length)); }
.flatMap(data -> service.setBinaryData(endpoint, id, data, length));
public Mono<Void> runAsync() { return Mono.fromSupplier(binaryDataSupplier) .flatMap(data -> service.setBinaryData(endpoint, id, data, length)); }
class BinaryDataSendTest extends RestProxyTestBase<CorePerfStressOptions> { private final long length; private final Supplier<BinaryData> binaryDataSupplier; public BinaryDataSendTest(CorePerfStressOptions options) { super(options); length = options.getSize(); binaryDataSupplier = createBinaryDataSupplier(options); } @Override public void run() { runAsync().block(); } @Override }
class BinaryDataSendTest extends RestProxyTestBase<CorePerfStressOptions> { private final long length; private final Supplier<BinaryData> binaryDataSupplier; public BinaryDataSendTest(CorePerfStressOptions options) { super(options); length = options.getSize(); binaryDataSupplier = createBinaryDataSupplier(options); } @Override public void run() { runAsync().block(); } @Override }
In Java8, `flip()` method returns a class of type Buffer. But in Java 9+, it returns a type of ByteBuffer. So we split this up to avoid the compilation errors.
private static Hashed computeHash(byte[] data, int seed1, int seed2) { int a = (0xdeadbeef + data.length + seed1); int b = a; int c = a + seed2; final ByteBuffer buffer = ByteBuffer.allocate(data.length) .put(data); buffer.flip(); buffer.order(ByteOrder.LITTLE_ENDIAN); int index = 0; int size = data.length; while (size > 12) { a += buffer.getInt(index); b += buffer.getInt(index + 4); c += buffer.getInt(index + 8); a -= c; a ^= (c << 4) | (c >>> 28); c += b; b -= a; b ^= (a << 6) | (a >>> 26); a += c; c -= b; c ^= (b << 8) | (b >>> 24); b += a; a -= c; a ^= (c << 16) | (c >>> 16); c += b; b -= a; b ^= (a << 19) | (a >>> 13); a += c; c -= b; c ^= (b << 4) | (b >>> 28); b += a; index += 12; size -= 12; } switch (size) { case 12: a += buffer.getInt(index); b += buffer.getInt(index + 4); c += buffer.getInt(index + 8); break; case 11: c += data[index + 10] << 16; case 10: c += data[index + 9] << 8; case 9: c += data[index + 8]; case 8: b += buffer.getInt(index + 4); a += buffer.getInt(index); break; case 7: b += data[index + 6] << 16; case 6: b += data[index + 5] << 8; case 5: b += data[index + 4]; case 4: a += buffer.getInt(index); break; case 3: a += data[index + 2] << 16; case 2: a += data[index + 1] << 8; case 1: a += data[index]; break; case 0: return new Hashed(c, b); default: break; } c ^= b; c -= (b << 14) | (b >>> 18); a ^= c; a -= (c << 11) | (c >>> 21); b ^= a; b -= (a << 25) | (a >>> 7); c ^= b; c -= (b << 16) | (b >>> 16); a ^= c; a -= (c << 4) | (c >>> 28); b ^= a; b -= (a << 14) | (a >>> 18); c ^= b; c -= (b << 24) | (b >>> 8); return new Hashed(c, b); }
buffer.flip();
private static Hashed computeHash(byte[] data, int seed1, int seed2) { int a = (0xdeadbeef + data.length + seed1); int b = a; int c = a + seed2; final ByteBuffer buffer = ByteBuffer.allocate(data.length) .put(data); buffer.flip(); buffer.order(ByteOrder.LITTLE_ENDIAN); int index = 0; int size = data.length; while (size > 12) { a += buffer.getInt(index); b += buffer.getInt(index + 4); c += buffer.getInt(index + 8); a -= c; a ^= (c << 4) | (c >>> 28); c += b; b -= a; b ^= (a << 6) | (a >>> 26); a += c; c -= b; c ^= (b << 8) | (b >>> 24); b += a; a -= c; a ^= (c << 16) | (c >>> 16); c += b; b -= a; b ^= (a << 19) | (a >>> 13); a += c; c -= b; c ^= (b << 4) | (b >>> 28); b += a; index += 12; size -= 12; } switch (size) { case 12: a += buffer.getInt(index); b += buffer.getInt(index + 4); c += buffer.getInt(index + 8); break; case 11: c += data[index + 10] << 16; case 10: c += data[index + 9] << 8; case 9: c += data[index + 8]; case 8: b += buffer.getInt(index + 4); a += buffer.getInt(index); break; case 7: b += data[index + 6] << 16; case 6: b += data[index + 5] << 8; case 5: b += data[index + 4]; case 4: a += buffer.getInt(index); break; case 3: a += data[index + 2] << 16; case 2: a += data[index + 1] << 8; case 1: a += data[index]; break; case 0: return new Hashed(c, b); default: break; } c ^= b; c -= (b << 14) | (b >>> 18); a ^= c; a -= (c << 11) | (c >>> 21); b ^= a; b -= (a << 25) | (a >>> 7); c ^= b; c -= (b << 16) | (b >>> 16); a ^= c; a -= (c << 4) | (c >>> 28); b ^= a; b -= (a << 14) | (a >>> 18); c ^= b; c -= (b << 24) | (b >>> 8); return new Hashed(c, b); }
class PartitionResolver { private static final ClientLogger LOGGER = new ClientLogger(PartitionResolver.class); private static final int STARTING_INDEX = -1; private final AtomicInteger partitionAssignmentIndex = new AtomicInteger(STARTING_INDEX); /** * Assigns a partition using a round-robin approach. * * @param partitions The set of available partitions. * * @return The zero-based index of the selected partition from the available set. */ String assignRoundRobin(String[] partitions) { Objects.requireNonNull(partitions, "'partitions' cannot be null."); if (partitions.length == 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitions' cannot be empty.")); } final int currentIndex = partitionAssignmentIndex.accumulateAndGet(1, (current, added) -> { try { return Math.addExact(current, added); } catch (ArithmeticException e) { LOGGER.info("Overflowed incrementing index. Rolling over.", e); return STARTING_INDEX + added; } }); return partitions[(currentIndex % partitions.length)]; } /** * Assigns a partition using a hash-based approach based on the provided {@code partitionKey}. * * @param partitionKey The partition key. * @param partitions The set of available partitions. * * @return The zero-based index of the selected partition from the available set. */ String assignForPartitionKey(String partitionKey, String[] partitions) { final short hashValue = generateHashCode(partitionKey); final int index = Math.abs(hashValue % partitions.length); return partitions[index]; } /** * Generates a hashcode for the partition key using Jenkins' lookup3 algorithm. * * This implementation is a direct port of the Event Hubs service code; it is intended to match the gateway hashing * algorithm as closely as possible and should not be adjusted without careful consideration. * * @param partitionKey The partition key. * * @return The generated hash code. */ static short generateHashCode(String partitionKey) { if (partitionKey == null) { return 0; } final byte[] bytes = partitionKey.getBytes(StandardCharsets.UTF_8); final Hashed hashed = computeHash(bytes, 0, 0); final int i = hashed.getHash1() ^ hashed.getHash2(); return Integer.valueOf(i).shortValue(); } /** * Computes a hash value using Jenkins' lookup3 algorithm. * * This implementation is a direct port of the Event Hubs service code; it is intended to match the gateway hashing * algorithm as closely as possible and should not be adjusted without careful consideration. * * NOTE: Suppressing fallthrough warning for switch-case because we want it to fall into the subsequent cases. * * @param data The data to base the hash on. * @param seed1 Seed value for the first hash. * @param seed2 Seed value for the second hash. * * @return An object containing the computed hash for {@code seed1} and {@code seed2}. */ @SuppressWarnings("fallthrough") /** * Class that holds the hash values from the lookup algorithm. */ private static class Hashed { private final int hash1; private final int hash2; Hashed(int hash1, int hash2) { this.hash1 = hash1; this.hash2 = hash2; } public int getHash1() { return hash1; } public int getHash2() { return hash2; } } }
class PartitionResolver { private static final ClientLogger LOGGER = new ClientLogger(PartitionResolver.class); private static final int STARTING_INDEX = -1; private final AtomicInteger partitionAssignmentIndex = new AtomicInteger(STARTING_INDEX); /** * Assigns a partition using a round-robin approach. * * @param partitions The set of available partitions. * * @return The zero-based index of the selected partition from the available set. */ String assignRoundRobin(String[] partitions) { Objects.requireNonNull(partitions, "'partitions' cannot be null."); if (partitions.length == 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'partitions' cannot be empty.")); } final int currentIndex = partitionAssignmentIndex.accumulateAndGet(1, (current, added) -> { try { return Math.addExact(current, added); } catch (ArithmeticException e) { LOGGER.info("Overflowed incrementing index. Rolling over.", e); return STARTING_INDEX + added; } }); return partitions[(currentIndex % partitions.length)]; } /** * Assigns a partition using a hash-based approach based on the provided {@code partitionKey}. * * @param partitionKey The partition key. * @param partitions The set of available partitions. * * @return The zero-based index of the selected partition from the available set. */ String assignForPartitionKey(String partitionKey, String[] partitions) { final short hashValue = generateHashCode(partitionKey); final int index = Math.abs(hashValue % partitions.length); return partitions[index]; } /** * Generates a hashcode for the partition key using Jenkins' lookup3 algorithm. * * This implementation is a direct port of the Event Hubs service code; it is intended to match the gateway hashing * algorithm as closely as possible and should not be adjusted without careful consideration. * * @param partitionKey The partition key. * * @return The generated hash code. */ static short generateHashCode(String partitionKey) { if (partitionKey == null) { return 0; } final byte[] bytes = partitionKey.getBytes(StandardCharsets.UTF_8); final Hashed hashed = computeHash(bytes, 0, 0); final int i = hashed.getHash1() ^ hashed.getHash2(); return Integer.valueOf(i).shortValue(); } /** * Computes a hash value using Jenkins' lookup3 algorithm. * * This implementation is a direct port of the Event Hubs service code; it is intended to match the gateway hashing * algorithm as closely as possible and should not be adjusted without careful consideration. * * NOTE: Suppressing fallthrough warning for switch-case because we want it to fall into the subsequent cases. * * @param data The data to base the hash on. * @param seed1 Seed value for the first hash. * @param seed2 Seed value for the second hash. * * @return An object containing the computed hash for {@code seed1} and {@code seed2}. */ @SuppressWarnings("fallthrough") /** * Class that holds the hash values from the lookup algorithm. */ private static class Hashed { private final int hash1; private final int hash2; Hashed(int hash1, int hash2) { this.hash1 = hash1; this.hash2 = hash2; } public int getHash1() { return hash1; } public int getHash2() { return hash2; } } }
We have `subscription.request(n)` when downstream request, do we still need to `request(1L)` here?
public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } }
subscription.request(1L);
public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (added) { return; } publishDownstream(); synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } } /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose("Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); if (added) { return; } publishDownstream(); added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } } /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose(previous + ": Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
add some log when eventData is null?
private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (added) { return; } publishDownstream(); synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } }
} else if (eventData == null) {
private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); if (added) { return; } publishDownstream(); added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } } @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose("Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } } @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose(previous + ": Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
Good catch. I removed it from this method.
public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } }
subscription.request(1L);
public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (added) { return; } publishDownstream(); synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } } /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose("Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); if (added) { return; } publishDownstream(); added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } } /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose(previous + ": Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
I added a comment since it is a normal path after maxWaitTime has elapsed.
private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (added) { return; } publishDownstream(); synchronized (lock) { added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } }
} else if (eventData == null) {
private void updateOrPublishBatch(EventData eventData, boolean alwaysPublish) { if (alwaysPublish) { publishDownstream(); return; } else if (eventData == null) { return; } boolean added; synchronized (lock) { added = currentBatch.tryAdd(eventData); if (added) { return; } publishDownstream(); added = currentBatch.tryAdd(eventData); } if (!added) { final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, "EventData exceeded maximum size.", new AmqpErrorContext(namespace)); onError(error); } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } } @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose("Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
class EventDataAggregatorMain implements Subscription, CoreSubscriber<EventData> { /** * The number of requested EventDataBatches. */ private volatile long requested; private static final AtomicLongFieldUpdater<EventDataAggregatorMain> REQUESTED = AtomicLongFieldUpdater.newUpdater(EventDataAggregatorMain.class, "requested"); private static final Duration MAX_TIME = Duration.ofMillis(Long.MAX_VALUE); private final Sinks.Many<Long> eventSink; private final Disposable disposable; private final AtomicBoolean isCompleted = new AtomicBoolean(false); private final CoreSubscriber<? super EventDataBatch> downstream; private final ClientLogger logger; private final Supplier<EventDataBatch> batchSupplier; private final String namespace; private final Object lock = new Object(); private Subscription subscription; private EventDataBatch currentBatch; EventDataAggregatorMain(CoreSubscriber<? super EventDataBatch> downstream, String namespace, BufferedProducerClientOptions options, Supplier<EventDataBatch> batchSupplier, ClientLogger logger) { this.namespace = namespace; this.downstream = downstream; this.logger = logger; this.batchSupplier = batchSupplier; this.currentBatch = batchSupplier.get(); this.eventSink = Sinks.many().unicast().onBackpressureError(); this.disposable = eventSink.asFlux() .switchMap(value -> { if (value == 0) { return Flux.interval(MAX_TIME, MAX_TIME); } else { return Flux.interval(options.getMaxWaitTime(), options.getMaxWaitTime()); } }) .subscribe(next -> { logger.verbose("Time elapsed. Publishing batch."); updateOrPublishBatch(null, true); }); } /** * Request a number of {@link EventDataBatch}. * * @param n Number of batches requested. */ @Override public void request(long n) { if (!Operators.validate(n)) { return; } Operators.addCap(REQUESTED, this, n); subscription.request(n); } /** * Cancels the subscription upstream. */ @Override public void cancel() { subscription.cancel(); updateOrPublishBatch(null, true); downstream.onComplete(); disposable.dispose(); } @Override public void onSubscribe(Subscription s) { if (subscription != null) { logger.warning("Subscription was already set. Cancelling existing subscription."); subscription.cancel(); } else { subscription = s; downstream.onSubscribe(this); } } @Override public void onNext(EventData eventData) { updateOrPublishBatch(eventData, false); eventSink.emitNext(1L, Sinks.EmitFailureHandler.FAIL_FAST); final long left = REQUESTED.get(this); if (left > 0) { subscription.request(1L); } } @Override public void onError(Throwable t) { if (!isCompleted.compareAndSet(false, true)) { Operators.onErrorDropped(t, downstream.currentContext()); return; } updateOrPublishBatch(null, true); downstream.onError(t); } /** * Upstream signals a completion. */ @Override public void onComplete() { if (isCompleted.compareAndSet(false, true)) { updateOrPublishBatch(null, true); downstream.onComplete(); } } /** * @param eventData EventData to add to or null if there are no events to add to the batch. * @param alwaysPublish {@code true} to always push batch downstream. {@code false}, otherwise. */ /** * Publishes batch downstream if there are events in the batch and updates it. */ private void publishDownstream() { EventDataBatch previous = null; try { synchronized (lock) { previous = this.currentBatch; if (previous == null) { logger.warning("Batch should not be null, setting a new batch."); this.currentBatch = batchSupplier.get(); return; } else if (previous.getEvents().isEmpty()) { return; } downstream.onNext(previous); final long batchesLeft = REQUESTED.updateAndGet(this, (v) -> { if (v == Long.MAX_VALUE) { return v; } else { return v - 1; } }); logger.verbose(previous + ": Batch published. Requested batches left: {}", batchesLeft); if (!isCompleted.get()) { this.currentBatch = batchSupplier.get(); } else { logger.verbose("Aggregator is completed. Not setting another batch."); this.currentBatch = null; } } } catch (Throwable e) { final Throwable error = Operators.onNextError(previous, e, downstream.currentContext(), subscription); logger.warning("Unable to push batch downstream to publish.", error); if (error != null) { onError(error); } } } }
nit: should we put this in some other util class?
private static List<Object> convertToListOrEmptyList(Map<String, Object> parameters, String key) { List<Object> listObjects = CASE_INSENSITIVE_MAPPER.convertValue(parameters.get(key), new TypeReference<List<Object>>() { }); return listObjects == null ? emptyList() : listObjects; }
}
private static List<Object> convertToListOrEmptyList(Map<String, Object> parameters, String key) { List<Object> listObjects = CASE_INSENSITIVE_MAPPER.convertValue(parameters.get(key), new TypeReference<List<Object>>() { }); return listObjects == null ? emptyList() : listObjects; }
class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationPropertySource.class); private static final String USERS = "users"; private static final String USERS_CAPS = "Users"; private static final String AUDIENCE = "Audience"; private static final String GROUPS = "groups"; private static final String GROUPS_CAPS = "Groups"; private static final String TARGETING_FILTER = "targetingFilter"; private static final String DEFAULT_ROLLOUT_PERCENTAGE = "defaultRolloutPercentage"; private static final String DEFAULT_ROLLOUT_PERCENTAGE_CAPS = "DefaultRolloutPercentage"; private static final ObjectMapper CASE_INSENSITIVE_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); private static final ObjectMapper FEATURE_MAPPER = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE).build(); private final AppConfigurationStoreSelects selectedKeys; private final List<String> profiles; private final Map<String, Object> properties = new LinkedHashMap<>(); private final AppConfigurationProperties appConfigurationProperties; private final Map<String, KeyVaultClient> keyVaultClients; private final AppConfigurationReplicaClient replicaClient; private final KeyVaultCredentialProvider keyVaultCredentialProvider; private final SecretClientBuilderSetup keyVaultClientProvider; private final KeyVaultSecretProvider keyVaultSecretProvider; private final AppConfigurationProviderProperties appProperties; private final FeatureFlagStore featureStore; AppConfigurationPropertySource(ConfigStore configStore, AppConfigurationStoreSelects selectedKeys, List<String> profiles, AppConfigurationProperties appConfigurationProperties, AppConfigurationReplicaClient replicaClient, AppConfigurationProviderProperties appProperties, KeyVaultCredentialProvider keyVaultCredentialProvider, SecretClientBuilderSetup keyVaultClientProvider, KeyVaultSecretProvider keyVaultSecretProvider) { super( selectedKeys.getKeyFilter() + configStore.getEndpoint() + "/" + selectedKeys.getLabelFilterText(profiles)); this.featureStore = configStore.getFeatureFlags(); this.selectedKeys = selectedKeys; this.profiles = profiles; this.appConfigurationProperties = appConfigurationProperties; this.appProperties = appProperties; this.keyVaultClients = new HashMap<>(); this.replicaClient = replicaClient; this.keyVaultCredentialProvider = keyVaultCredentialProvider; this.keyVaultClientProvider = keyVaultClientProvider; this.keyVaultSecretProvider = keyVaultSecretProvider; } @Override public String[] getPropertyNames() { Set<String> keySet = properties.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override public Object getProperty(String name) { return properties.get(name); } /** * <p> * Gets settings from Azure/Cache to set as configurations. Updates the cache. * </p> * * <p> * <b>Note</b>: Doesn't update Feature Management, just stores values in cache. Call {@code initFeatures} to update * Feature Management, but make sure its done in the last {@code AppConfigurationPropertySource} * AppConfigurationPropertySource}
class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationPropertySource.class); private static final String USERS = "users"; private static final String USERS_CAPS = "Users"; private static final String AUDIENCE = "Audience"; private static final String GROUPS = "groups"; private static final String GROUPS_CAPS = "Groups"; private static final String TARGETING_FILTER = "targetingFilter"; private static final String DEFAULT_ROLLOUT_PERCENTAGE = "defaultRolloutPercentage"; private static final String DEFAULT_ROLLOUT_PERCENTAGE_CAPS = "DefaultRolloutPercentage"; private static final ObjectMapper CASE_INSENSITIVE_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); private static final ObjectMapper FEATURE_MAPPER = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE).build(); private final AppConfigurationStoreSelects selectedKeys; private final List<String> profiles; private final Map<String, Object> properties = new LinkedHashMap<>(); private final AppConfigurationProperties appConfigurationProperties; private final Map<String, KeyVaultClient> keyVaultClients; private final AppConfigurationReplicaClient replicaClient; private final KeyVaultCredentialProvider keyVaultCredentialProvider; private final SecretClientBuilderSetup keyVaultClientProvider; private final KeyVaultSecretProvider keyVaultSecretProvider; private final AppConfigurationProviderProperties appProperties; private final FeatureFlagStore featureStore; AppConfigurationPropertySource(ConfigStore configStore, AppConfigurationStoreSelects selectedKeys, List<String> profiles, AppConfigurationProperties appConfigurationProperties, AppConfigurationReplicaClient replicaClient, AppConfigurationProviderProperties appProperties, KeyVaultCredentialProvider keyVaultCredentialProvider, SecretClientBuilderSetup keyVaultClientProvider, KeyVaultSecretProvider keyVaultSecretProvider) { super( selectedKeys.getKeyFilter() + configStore.getEndpoint() + "/" + selectedKeys.getLabelFilterText(profiles)); this.featureStore = configStore.getFeatureFlags(); this.selectedKeys = selectedKeys; this.profiles = profiles; this.appConfigurationProperties = appConfigurationProperties; this.appProperties = appProperties; this.keyVaultClients = new HashMap<>(); this.replicaClient = replicaClient; this.keyVaultCredentialProvider = keyVaultCredentialProvider; this.keyVaultClientProvider = keyVaultClientProvider; this.keyVaultSecretProvider = keyVaultSecretProvider; } @Override public String[] getPropertyNames() { Set<String> keySet = properties.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override public Object getProperty(String name) { return properties.get(name); } /** * <p> * Gets settings from Azure/Cache to set as configurations. Updates the cache. * </p> * * <p> * <b>Note</b>: Doesn't update Feature Management, just stores values in cache. Call {@code initFeatures} to update * Feature Management, but make sure its done in the last {@code AppConfigurationPropertySource} * AppConfigurationPropertySource}
Shouldn't the return type of `parseJsonSetting()` be Map?
FeatureSet initProperties(FeatureSet featureSet) throws IOException, AppConfigurationStatusException { SettingSelector settingSelector = new SettingSelector(); PagedIterable<ConfigurationSetting> features = null; if (featureStore.getEnabled()) { settingSelector.setKeyFilter(featureStore.getKeyFilter()).setLabelFilter(featureStore.getLabelFilter()); features = replicaClient.listSettings(settingSelector); } List<String> labels = Arrays.asList(selectedKeys.getLabelFilter(profiles)); Collections.reverse(labels); for (String label : labels) { settingSelector = new SettingSelector().setKeyFilter(selectedKeys.getKeyFilter() + "*") .setLabelFilter(label); PagedIterable<ConfigurationSetting> settings = replicaClient.listSettings(settingSelector); for (ConfigurationSetting setting : settings) { String key = setting.getKey().trim().substring(selectedKeys.getKeyFilter().length()).replace('/', '.'); if (setting instanceof SecretReferenceConfigurationSetting) { String entry = getKeyVaultEntry((SecretReferenceConfigurationSetting) setting); if (entry != null) { properties.put(key, entry); } } else if (StringUtils.hasText(setting.getContentType()) && JsonConfigurationParser.isJsonContentType(setting.getContentType())) { HashMap<String, Object> jsonSettings = JsonConfigurationParser.parseJsonSetting(setting); for (Entry<String, Object> jsonSetting : jsonSettings.entrySet()) { key = jsonSetting.getKey().trim().substring(selectedKeys.getKeyFilter().length()); properties.put(key, jsonSetting.getValue()); } } else { properties.put(key, setting.getValue()); } } } return addToFeatureSet(featureSet, features); }
HashMap<String, Object> jsonSettings = JsonConfigurationParser.parseJsonSetting(setting);
FeatureSet initProperties(FeatureSet featureSet) throws IOException, AppConfigurationStatusException { SettingSelector settingSelector = new SettingSelector(); List<ConfigurationSetting> features = null; if (featureStore.getEnabled()) { settingSelector.setKeyFilter(featureStore.getKeyFilter()).setLabelFilter(featureStore.getLabelFilter()); features = replicaClient.listConfigurationSettings(settingSelector); } List<String> labels = Arrays.asList(selectedKeys.getLabelFilter(profiles)); Collections.reverse(labels); for (String label : labels) { settingSelector = new SettingSelector().setKeyFilter(selectedKeys.getKeyFilter() + "*") .setLabelFilter(label); List<ConfigurationSetting> settings = replicaClient.listConfigurationSettings(settingSelector); for (ConfigurationSetting setting : settings) { String key = setting.getKey().trim().substring(selectedKeys.getKeyFilter().length()).replace('/', '.'); if (setting instanceof SecretReferenceConfigurationSetting) { String entry = getKeyVaultEntry((SecretReferenceConfigurationSetting) setting); if (entry != null) { properties.put(key, entry); } } else if (StringUtils.hasText(setting.getContentType()) && JsonConfigurationParser.isJsonContentType(setting.getContentType())) { Map<String, Object> jsonSettings = JsonConfigurationParser.parseJsonSetting(setting); for (Entry<String, Object> jsonSetting : jsonSettings.entrySet()) { key = jsonSetting.getKey().trim().substring(selectedKeys.getKeyFilter().length()); properties.put(key, jsonSetting.getValue()); } } else { properties.put(key, setting.getValue()); } } } return addToFeatureSet(featureSet, features); }
class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationPropertySource.class); private static final String USERS = "users"; private static final String USERS_CAPS = "Users"; private static final String AUDIENCE = "Audience"; private static final String GROUPS = "groups"; private static final String GROUPS_CAPS = "Groups"; private static final String TARGETING_FILTER = "targetingFilter"; private static final String DEFAULT_ROLLOUT_PERCENTAGE = "defaultRolloutPercentage"; private static final String DEFAULT_ROLLOUT_PERCENTAGE_CAPS = "DefaultRolloutPercentage"; private static final ObjectMapper CASE_INSENSITIVE_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); private static final ObjectMapper FEATURE_MAPPER = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE).build(); private final AppConfigurationStoreSelects selectedKeys; private final List<String> profiles; private final Map<String, Object> properties = new LinkedHashMap<>(); private final AppConfigurationProperties appConfigurationProperties; private final Map<String, KeyVaultClient> keyVaultClients; private final AppConfigurationReplicaClient replicaClient; private final KeyVaultCredentialProvider keyVaultCredentialProvider; private final SecretClientBuilderSetup keyVaultClientProvider; private final KeyVaultSecretProvider keyVaultSecretProvider; private final AppConfigurationProviderProperties appProperties; private final FeatureFlagStore featureStore; AppConfigurationPropertySource(ConfigStore configStore, AppConfigurationStoreSelects selectedKeys, List<String> profiles, AppConfigurationProperties appConfigurationProperties, AppConfigurationReplicaClient replicaClient, AppConfigurationProviderProperties appProperties, KeyVaultCredentialProvider keyVaultCredentialProvider, SecretClientBuilderSetup keyVaultClientProvider, KeyVaultSecretProvider keyVaultSecretProvider) { super( selectedKeys.getKeyFilter() + configStore.getEndpoint() + "/" + selectedKeys.getLabelFilterText(profiles)); this.featureStore = configStore.getFeatureFlags(); this.selectedKeys = selectedKeys; this.profiles = profiles; this.appConfigurationProperties = appConfigurationProperties; this.appProperties = appProperties; this.keyVaultClients = new HashMap<>(); this.replicaClient = replicaClient; this.keyVaultCredentialProvider = keyVaultCredentialProvider; this.keyVaultClientProvider = keyVaultClientProvider; this.keyVaultSecretProvider = keyVaultSecretProvider; } private static List<Object> convertToListOrEmptyList(Map<String, Object> parameters, String key) { List<Object> listObjects = CASE_INSENSITIVE_MAPPER.convertValue(parameters.get(key), new TypeReference<List<Object>>() { }); return listObjects == null ? emptyList() : listObjects; } @Override public String[] getPropertyNames() { Set<String> keySet = properties.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override public Object getProperty(String name) { return properties.get(name); } /** * <p> * Gets settings from Azure/Cache to set as configurations. Updates the cache. * </p> * * <p> * <b>Note</b>: Doesn't update Feature Management, just stores values in cache. Call {@code initFeatures} to update * Feature Management, but make sure its done in the last {@code AppConfigurationPropertySource} * AppConfigurationPropertySource}
class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationPropertySource.class); private static final String USERS = "users"; private static final String USERS_CAPS = "Users"; private static final String AUDIENCE = "Audience"; private static final String GROUPS = "groups"; private static final String GROUPS_CAPS = "Groups"; private static final String TARGETING_FILTER = "targetingFilter"; private static final String DEFAULT_ROLLOUT_PERCENTAGE = "defaultRolloutPercentage"; private static final String DEFAULT_ROLLOUT_PERCENTAGE_CAPS = "DefaultRolloutPercentage"; private static final ObjectMapper CASE_INSENSITIVE_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); private static final ObjectMapper FEATURE_MAPPER = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE).build(); private final AppConfigurationStoreSelects selectedKeys; private final List<String> profiles; private final Map<String, Object> properties = new LinkedHashMap<>(); private final AppConfigurationProperties appConfigurationProperties; private final Map<String, KeyVaultClient> keyVaultClients; private final AppConfigurationReplicaClient replicaClient; private final KeyVaultCredentialProvider keyVaultCredentialProvider; private final SecretClientBuilderSetup keyVaultClientProvider; private final KeyVaultSecretProvider keyVaultSecretProvider; private final AppConfigurationProviderProperties appProperties; private final FeatureFlagStore featureStore; AppConfigurationPropertySource(ConfigStore configStore, AppConfigurationStoreSelects selectedKeys, List<String> profiles, AppConfigurationProperties appConfigurationProperties, AppConfigurationReplicaClient replicaClient, AppConfigurationProviderProperties appProperties, KeyVaultCredentialProvider keyVaultCredentialProvider, SecretClientBuilderSetup keyVaultClientProvider, KeyVaultSecretProvider keyVaultSecretProvider) { super( selectedKeys.getKeyFilter() + configStore.getEndpoint() + "/" + selectedKeys.getLabelFilterText(profiles)); this.featureStore = configStore.getFeatureFlags(); this.selectedKeys = selectedKeys; this.profiles = profiles; this.appConfigurationProperties = appConfigurationProperties; this.appProperties = appProperties; this.keyVaultClients = new HashMap<>(); this.replicaClient = replicaClient; this.keyVaultCredentialProvider = keyVaultCredentialProvider; this.keyVaultClientProvider = keyVaultClientProvider; this.keyVaultSecretProvider = keyVaultSecretProvider; } private static List<Object> convertToListOrEmptyList(Map<String, Object> parameters, String key) { List<Object> listObjects = CASE_INSENSITIVE_MAPPER.convertValue(parameters.get(key), new TypeReference<List<Object>>() { }); return listObjects == null ? emptyList() : listObjects; } @Override public String[] getPropertyNames() { Set<String> keySet = properties.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override public Object getProperty(String name) { return properties.get(name); } /** * <p> * Gets settings from Azure/Cache to set as configurations. Updates the cache. * </p> * * <p> * <b>Note</b>: Doesn't update Feature Management, just stores values in cache. Call {@code initFeatures} to update * Feature Management, but make sure its done in the last {@code AppConfigurationPropertySource} * AppConfigurationPropertySource}
This changes in the 4.0 version, so if this is still an issue then we can change it. Feature Management gets it own property sources in 4.0.
private static List<Object> convertToListOrEmptyList(Map<String, Object> parameters, String key) { List<Object> listObjects = CASE_INSENSITIVE_MAPPER.convertValue(parameters.get(key), new TypeReference<List<Object>>() { }); return listObjects == null ? emptyList() : listObjects; }
}
private static List<Object> convertToListOrEmptyList(Map<String, Object> parameters, String key) { List<Object> listObjects = CASE_INSENSITIVE_MAPPER.convertValue(parameters.get(key), new TypeReference<List<Object>>() { }); return listObjects == null ? emptyList() : listObjects; }
class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationPropertySource.class); private static final String USERS = "users"; private static final String USERS_CAPS = "Users"; private static final String AUDIENCE = "Audience"; private static final String GROUPS = "groups"; private static final String GROUPS_CAPS = "Groups"; private static final String TARGETING_FILTER = "targetingFilter"; private static final String DEFAULT_ROLLOUT_PERCENTAGE = "defaultRolloutPercentage"; private static final String DEFAULT_ROLLOUT_PERCENTAGE_CAPS = "DefaultRolloutPercentage"; private static final ObjectMapper CASE_INSENSITIVE_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); private static final ObjectMapper FEATURE_MAPPER = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE).build(); private final AppConfigurationStoreSelects selectedKeys; private final List<String> profiles; private final Map<String, Object> properties = new LinkedHashMap<>(); private final AppConfigurationProperties appConfigurationProperties; private final Map<String, KeyVaultClient> keyVaultClients; private final AppConfigurationReplicaClient replicaClient; private final KeyVaultCredentialProvider keyVaultCredentialProvider; private final SecretClientBuilderSetup keyVaultClientProvider; private final KeyVaultSecretProvider keyVaultSecretProvider; private final AppConfigurationProviderProperties appProperties; private final FeatureFlagStore featureStore; AppConfigurationPropertySource(ConfigStore configStore, AppConfigurationStoreSelects selectedKeys, List<String> profiles, AppConfigurationProperties appConfigurationProperties, AppConfigurationReplicaClient replicaClient, AppConfigurationProviderProperties appProperties, KeyVaultCredentialProvider keyVaultCredentialProvider, SecretClientBuilderSetup keyVaultClientProvider, KeyVaultSecretProvider keyVaultSecretProvider) { super( selectedKeys.getKeyFilter() + configStore.getEndpoint() + "/" + selectedKeys.getLabelFilterText(profiles)); this.featureStore = configStore.getFeatureFlags(); this.selectedKeys = selectedKeys; this.profiles = profiles; this.appConfigurationProperties = appConfigurationProperties; this.appProperties = appProperties; this.keyVaultClients = new HashMap<>(); this.replicaClient = replicaClient; this.keyVaultCredentialProvider = keyVaultCredentialProvider; this.keyVaultClientProvider = keyVaultClientProvider; this.keyVaultSecretProvider = keyVaultSecretProvider; } @Override public String[] getPropertyNames() { Set<String> keySet = properties.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override public Object getProperty(String name) { return properties.get(name); } /** * <p> * Gets settings from Azure/Cache to set as configurations. Updates the cache. * </p> * * <p> * <b>Note</b>: Doesn't update Feature Management, just stores values in cache. Call {@code initFeatures} to update * Feature Management, but make sure its done in the last {@code AppConfigurationPropertySource} * AppConfigurationPropertySource}
class AppConfigurationPropertySource extends EnumerablePropertySource<ConfigurationClient> { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationPropertySource.class); private static final String USERS = "users"; private static final String USERS_CAPS = "Users"; private static final String AUDIENCE = "Audience"; private static final String GROUPS = "groups"; private static final String GROUPS_CAPS = "Groups"; private static final String TARGETING_FILTER = "targetingFilter"; private static final String DEFAULT_ROLLOUT_PERCENTAGE = "defaultRolloutPercentage"; private static final String DEFAULT_ROLLOUT_PERCENTAGE_CAPS = "DefaultRolloutPercentage"; private static final ObjectMapper CASE_INSENSITIVE_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); private static final ObjectMapper FEATURE_MAPPER = JsonMapper.builder() .propertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE).build(); private final AppConfigurationStoreSelects selectedKeys; private final List<String> profiles; private final Map<String, Object> properties = new LinkedHashMap<>(); private final AppConfigurationProperties appConfigurationProperties; private final Map<String, KeyVaultClient> keyVaultClients; private final AppConfigurationReplicaClient replicaClient; private final KeyVaultCredentialProvider keyVaultCredentialProvider; private final SecretClientBuilderSetup keyVaultClientProvider; private final KeyVaultSecretProvider keyVaultSecretProvider; private final AppConfigurationProviderProperties appProperties; private final FeatureFlagStore featureStore; AppConfigurationPropertySource(ConfigStore configStore, AppConfigurationStoreSelects selectedKeys, List<String> profiles, AppConfigurationProperties appConfigurationProperties, AppConfigurationReplicaClient replicaClient, AppConfigurationProviderProperties appProperties, KeyVaultCredentialProvider keyVaultCredentialProvider, SecretClientBuilderSetup keyVaultClientProvider, KeyVaultSecretProvider keyVaultSecretProvider) { super( selectedKeys.getKeyFilter() + configStore.getEndpoint() + "/" + selectedKeys.getLabelFilterText(profiles)); this.featureStore = configStore.getFeatureFlags(); this.selectedKeys = selectedKeys; this.profiles = profiles; this.appConfigurationProperties = appConfigurationProperties; this.appProperties = appProperties; this.keyVaultClients = new HashMap<>(); this.replicaClient = replicaClient; this.keyVaultCredentialProvider = keyVaultCredentialProvider; this.keyVaultClientProvider = keyVaultClientProvider; this.keyVaultSecretProvider = keyVaultSecretProvider; } @Override public String[] getPropertyNames() { Set<String> keySet = properties.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override public Object getProperty(String name) { return properties.get(name); } /** * <p> * Gets settings from Azure/Cache to set as configurations. Updates the cache. * </p> * * <p> * <b>Note</b>: Doesn't update Feature Management, just stores values in cache. Call {@code initFeatures} to update * Feature Management, but make sure its done in the last {@code AppConfigurationPropertySource} * AppConfigurationPropertySource}
nit: We should not strictly cast it to ArrayList<String> here, instead keep it open to generic `List<String>` here. ``` List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream().map(Object::toString).collect(Collectors.toList()); ```
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream()
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
For better understanding for future, we should add a comment here on the else condition, where the sqlParameter will remain an empty array list.
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
}
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
@kushagraThapar I am not actually sure why that is there, I carried it over from the past functionality, but it seems odd to me, as if we set the parameter name to "@" alone it will surely break. Do you know why it is there/what the comment should be?
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
}
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
Done.
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream()
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
@trande4884 - what I meant was in the section of the code, where there is no else condition and the code will eventually create an empty `sqlParameter` list. ``` if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } ``` The reason it is here is because page query and sort queries are handled down below. so that's why we filter them here. But on second thought, I don't think the comment is really necessary, I think we can skip it and go with the implementation as it is.
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
}
public Object execute(final Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters); final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); String expandedQuery = query; List<SqlParameter> sqlParameters = new ArrayList<>(); for (int paramIndex = 0; paramIndex < parameters.length; paramIndex++) { Parameter queryParam = getQueryMethod().getParameters().getParameter(paramIndex); if (parameters[paramIndex] instanceof Collection) { List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream() .map(Object::toString).collect(Collectors.toList()); List<String> expandedParamKeys = new ArrayList<>(); for (int arrayIndex = 0; arrayIndex < expandParam.size(); arrayIndex++) { String paramName = "@" + queryParam.getName().orElse("") + arrayIndex; expandedParamKeys.add(paramName); sqlParameters.add(new SqlParameter(paramName, toCosmosDbValue(expandParam.get(arrayIndex)))); } expandedQuery = expandedQuery.replaceAll("@" + queryParam.getName().orElse(""), String.join(",", expandedParamKeys)); } else { if (!Pageable.class.isAssignableFrom(queryParam.getType()) && !Sort.class.isAssignableFrom(queryParam.getType())) { sqlParameters.add(new SqlParameter("@" + queryParam.getName().orElse(""), toCosmosDbValue(parameters[paramIndex]))); } } } SqlQuerySpec querySpec = new SqlQuerySpec(expandedQuery, sqlParameters); if (isPageQuery()) { return this.operations.runPaginationQuery(querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isSliceQuery()) { return this.operations.runSliceQuery( querySpec, accessor.getPageable(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } else if (isCountQuery()) { final String container = ((CosmosEntityMetadata<?>) getQueryMethod().getEntityInformation()).getContainerName(); return this.operations.count(querySpec, container); } else { return this.operations.runQuery(querySpec, accessor.getSort(), processor.getReturnedType().getDomainType(), processor.getReturnedType().getReturnedType()); } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
class StringBasedCosmosQuery extends AbstractCosmosQuery { private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE); private final String query; /** * Constructor * @param queryMethod the CosmosQueryMethod * @param dbOperations the CosmosOperations */ public StringBasedCosmosQuery(CosmosQueryMethod queryMethod, CosmosOperations dbOperations) { super(queryMethod, dbOperations); this.query = queryMethod.getQueryAnnotation(); } @Override protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { return null; } @Override @Override protected boolean isDeleteQuery() { return false; } @Override protected boolean isExistsQuery() { return false; } @Override protected boolean isCountQuery() { return isCountQuery(query, getQueryMethod().getReturnedObjectType()); } static boolean isCountQuery(String query, Class<?> returnedType) { if (isCountQueryReturnType(returnedType)) { return COUNT_QUERY_PATTERN.matcher(query).matches(); } else { return false; } } private static boolean isCountQueryReturnType(Class<?> returnedType) { return returnedType == Long.class || returnedType == long.class || returnedType == Integer.class || returnedType == int.class; } }
does this work ? `Context` is immutable. Should this be `context = enableSyncRestProxy(context);` ? Please add tests that assert that we're hitting right api on the http client layer (@samvaity is doing that in app config please sync with her).
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; enableSyncRestProxy(context); return service.getSecret(vaultUrl, name, version == null ? "" : version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); }
enableSyncRestProxy(context);
public Response<KeyVaultSecret> getSecretWithResponse(String name, String version, Context context) { context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.getSecret(vaultUrl, name, version == null ? "" : version, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); }
class SecretClientImpl { private final String apiVersion; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final SecretService service; private final ClientLogger logger = new ClientLogger(SecretClientImpl.class); private final HttpPipeline pipeline; /** * Creates a SecretAsyncClient that uses {@code pipeline} to service requests * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. * @param version {@link SecretServiceVersion} of the service to be used when making requests. */ public SecretClientImpl(String vaultUrl, HttpPipeline pipeline, SecretServiceVersion version) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl; this.service = RestProxy.create(SecretService.class, pipeline); this.pipeline = pipeline; apiVersion = version.getVersion(); } /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return this.pipeline; } public Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * The interface defining all the services for {@link SecretAsyncClient} to be used * by the proxy service to perform REST calls. * * This is package-private so that these REST calls are transparent to the user. */ @Host("{url}") @ServiceInterface(name = "KeyVaultSecrets") public interface SecretService { @Put("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> setSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> getSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> getSecretPollerAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Patch("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<SecretProperties>> updateSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Delete("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<DeletedSecret>> deleteSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<DeletedSecret>> getDeletedSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<DeletedSecret>> getDeletedSecretPollerAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Delete("deletedsecrets/{secret-name}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<Void>> purgeDeletedSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("deletedsecrets/{secret-name}/recover") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> recoverDeletedSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/{secret-name}/backup") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<SecretBackup>> backupSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/restore") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> restoreSecretAsync(@HostParam("url") String url, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRestoreRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Get("secrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) Mono<PagedResponse<SecretProperties>> getSecretsAsync(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/versions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) Mono<PagedResponse<SecretProperties>> getSecretVersionsAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) Mono<PagedResponse<SecretProperties>> getSecretsAsync(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) Mono<PagedResponse<DeletedSecret>> getDeletedSecretsAsync(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) Mono<PagedResponse<DeletedSecret>> getDeletedSecretsAsync(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Put("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> setSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> getSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> getSecretPoller(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Patch("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<SecretProperties> updateSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Delete("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<DeletedSecret> deleteSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<DeletedSecret> getDeletedSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<DeletedSecret> getDeletedSecretPoller(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Delete("deletedsecrets/{secret-name}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<Void> purgeDeletedSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("deletedsecrets/{secret-name}/recover") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> recoverDeletedSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/{secret-name}/backup") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<SecretBackup> backupSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/restore") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> restoreSecret(@HostParam("url") String url, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRestoreRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Get("secrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) PagedResponse<SecretProperties> getSecrets(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/versions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) PagedResponse<SecretProperties> getSecretVersions(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) PagedResponse<SecretProperties> getSecrets(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) PagedResponse<DeletedSecret> getDeletedSecrets(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) PagedResponse<DeletedSecret> getDeletedSecrets(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); } /** * Creates a new secret in the key vault. * @param secret the secret to create. * @param context the context to use while executing request. * @return A {@link Mono} containing the Response with created secret. */ public Mono<Response<KeyVaultSecret>> setSecretWithResponseAsync(KeyVaultSecret secret, Context context) { SecretRequestParameters parameters = validateAndCreateSetSecretParameters(secret); context = context == null ? Context.NONE : context; return service.setSecretAsync(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.verbose("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } /** * Creates a new secret in the key vault. * @param secret the secret to create. * @param context the context to use while executing request. * @return the Response with created secret. */ public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { SecretRequestParameters parameters = validateAndCreateSetSecretParameters(secret); context = context == null ? Context.NONE : context; enableSyncRestProxy(context); return service.setSecret(vaultUrl, secret.getName(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } private SecretRequestParameters validateAndCreateSetSecretParameters(KeyVaultSecret secret) { Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return parameters; } /** * Creates a new secret in the key vault asynchronously. * @param name the secret of the secret. * @param value the value of the secret. * @param context the context to use while executing request. * @return A {@link Mono} containing the Response with created secret. */ public Mono<Response<KeyVaultSecret>> setSecretWithResponseAsync(String name, String value, Context context) { SecretRequestParameters parameters = new SecretRequestParameters().setValue(value); return service.setSecretAsync(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Setting secret - {}", name)) .doOnSuccess(response -> logger.verbose("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", name, error)); } /** * Creates a new secret in the key vault. * @param name the secret of the secret. * @param value the value of the secret. * @param context the context to use while executing request. * @return the Response with created secret. */ public Response<KeyVaultSecret> setSecretWithResponse(String name, String value, Context context) { SecretRequestParameters parameters = new SecretRequestParameters().setValue(value); enableSyncRestProxy(context); return service.setSecret(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public Mono<Response<KeyVaultSecret>> getSecretWithResponseAsync(String name, String version, Context context) { context = context == null ? Context.NONE : context; return service.getSecretAsync(vaultUrl, name, version == null ? "" : version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving secret - {}", name)) .doOnSuccess(response -> logger.verbose("Retrieved secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get secret - {}", name, error)); } public Mono<Response<SecretProperties>> updateSecretPropertiesWithResponseAsync(SecretProperties secretProperties, Context context) { SecretRequestParameters parameters = validateAndCreateUpdateSecretRequestParameters(secretProperties); context = context == null ? Context.NONE : context; return service.updateSecretAsync(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Updating secret - {}", secretProperties.getName())) .doOnSuccess(response -> logger.verbose("Updated secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update secret - {}", secretProperties.getName(), error)); } public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { SecretRequestParameters parameters = validateAndCreateUpdateSecretRequestParameters(secretProperties); context = context == null ? Context.NONE : context; enableSyncRestProxy(context); return service.updateSecret(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } private SecretRequestParameters validateAndCreateUpdateSecretRequestParameters(SecretProperties secretProperties) { Objects.requireNonNull(secretProperties, "The secret properties input parameter cannot be null."); return new SecretRequestParameters() .setTags(secretProperties.getTags()) .setContentType(secretProperties.getContentType()) .setSecretAttributes(new SecretRequestAttributes(secretProperties)); } public PollerFlux<DeletedSecret, Void> beginDeleteSecretAsync(String name) { return new PollerFlux<>(getDefaultPollingInterval(), activationOperation(name), createPollOperation(name), (pollingContext, firstResponse) -> Mono.empty(), (pollingContext) -> Mono.empty()); } private Function<PollingContext<DeletedSecret>, Mono<DeletedSecret>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteSecretWithResponseAsync(name, context)).flatMap(deletedSecretResponse -> Mono.just(deletedSecretResponse.getValue())); } /** * Polling operation to poll on create delete key operation status */ private Function<PollingContext<DeletedSecret>, Mono<PollResponse<DeletedSecret>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedSecretPollerAsync(vaultUrl, keyName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedSecretResponse -> { if (deletedSecretResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<DeletedSecret>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedSecretResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } private Mono<Response<DeletedSecret>> deleteSecretWithResponseAsync(String name, Context context) { return service.deleteSecretAsync(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Deleting secret - {}", name)) .doOnSuccess(response -> logger.verbose("Deleted secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete secret - {}", name, error)); } public Mono<Response<DeletedSecret>> getDeletedSecretWithResponseAsync(String name, Context context) { context = context == null ? Context.NONE : context; return service.getDeletedSecretAsync(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Retrieving deleted secret - {}", name)) .doOnSuccess(response -> logger.verbose("Retrieved deleted secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to retrieve deleted secret - {}", name, error)); } public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; enableSyncRestProxy(context); return service.getDeletedSecret(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public Mono<Response<Void>> purgeDeletedSecretWithResponseAsync(String name, Context context) { context = context == null ? Context.NONE : context; return service.purgeDeletedSecretAsync(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Purging deleted secret - {}", name)) .doOnSuccess(response -> logger.verbose("Purged deleted secret - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted secret - {}", name, error)); } public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; enableSyncRestProxy(context); return service.purgeDeletedSecret(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public PollerFlux<KeyVaultSecret, Void> beginRecoverDeletedSecretAsync(String name) { return new PollerFlux<>(getDefaultPollingInterval(), recoverActivationOperation(name), createRecoverPollOperation(name), (pollerContext, firstResponse) -> Mono.empty(), (pollingContext) -> Mono.empty()); } private Function<PollingContext<KeyVaultSecret>, Mono<KeyVaultSecret>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedSecretWithResponseAsync(name, context)).flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* Polling operation to poll on create delete key operation status. */ private Function<PollingContext<KeyVaultSecret>, Mono<PollResponse<KeyVaultSecret>>> createRecoverPollOperation(String secretName) { return pollingContext -> withContext(context -> service.getSecretPollerAsync(vaultUrl, secretName, "", apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(secretResponse -> { PollResponse<KeyVaultSecret> prePollResponse = pollingContext.getLatestResponse(); if (secretResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, prePollResponse.getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, secretResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } private Mono<Response<KeyVaultSecret>> recoverDeletedSecretWithResponseAsync(String name, Context context) { return service.recoverDeletedSecretAsync(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Recovering deleted secret - {}", name)) .doOnSuccess(response -> logger.verbose("Recovered deleted secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted secret - {}", name, error)); } public Mono<Response<byte[]>> backupSecretWithResponseAsync(String name, Context context) { context = context == null ? Context.NONE : context; return service.backupSecretAsync(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Backing up secret - {}", name)) .doOnSuccess(response -> logger.verbose("Backed up secret - {}", name)) .doOnError(error -> logger.warning("Failed to back up secret - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } public Response<byte[]> backupSecretWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; enableSyncRestProxy(context); Response<SecretBackup> secretBackupResponse = service. backupSecret(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); return new SimpleResponse<>(secretBackupResponse.getRequest(), secretBackupResponse.getStatusCode(), secretBackupResponse.getHeaders(), secretBackupResponse.getValue().getValue()); } public Mono<Response<KeyVaultSecret>> restoreSecretBackupWithResponseAsync(byte[] backup, Context context) { context = context == null ? Context.NONE : context; SecretRestoreRequestParameters parameters = new SecretRestoreRequestParameters().setSecretBackup(backup); return service.restoreSecretAsync(vaultUrl, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Attempting to restore secret")) .doOnSuccess(response -> logger.verbose("Restored secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore secret", error)); } public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { context = context == null ? Context.NONE : context; enableSyncRestProxy(context); SecretRestoreRequestParameters parameters = new SecretRestoreRequestParameters().setSecretBackup(backup); return service.restoreSecret(vaultUrl, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public PagedFlux<SecretProperties> listPropertiesOfSecretsAsync() { try { return new PagedFlux<>( () -> withContext(context -> listSecretsFirstPage(context)), continuationToken -> withContext(context -> listSecretsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } public PagedFlux<SecretProperties> listPropertiesOfSecretsAsync(Context context) { return new PagedFlux<>( () -> listSecretsFirstPage(context), continuationToken -> listSecretsNextPage(continuationToken, context)); } /* * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to * {@link SecretAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * @return A {@link Mono} of {@link PagedResponse<SecretProperties>} from the next page of results. */ private Mono<PagedResponse<SecretProperties>> listSecretsNextPage(String continuationToken, Context context) { try { return service.getSecretsAsync(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving the next secrets page - Page {}", continuationToken)) .doOnSuccess(response -> logger.verbose("Retrieved the next secrets page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next secrets page - Page {}", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<SecretProperties>> listSecretsFirstPage(Context context) { try { return service.getSecretsAsync(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Listing secrets")) .doOnSuccess(response -> logger.verbose("Listed secrets")) .doOnError(error -> logger.warning("Failed to list secrets", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } public PagedFlux<DeletedSecret> listDeletedSecretsAsync() { try { return new PagedFlux<>( () -> withContext(context -> listDeletedSecretsFirstPage(context)), continuationToken -> withContext(context -> listDeletedSecretsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } public PagedFlux<DeletedSecret> listDeletedSecretsAsync(Context context) { return new PagedFlux<>( () -> listDeletedSecretsFirstPage(context), continuationToken -> listDeletedSecretsNextPage(continuationToken, context)); } /** * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to * {@link SecretAsyncClient * * @param continuationToken The {@link Page * list operations. * @return A {@link Mono} of {@link PagedResponse} that contains {@link DeletedSecret} from the next page of * results. */ private Mono<PagedResponse<DeletedSecret>> listDeletedSecretsNextPage(String continuationToken, Context context) { try { return service.getDeletedSecretsAsync(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving the next deleted secrets page - Page {}", continuationToken)) .doOnSuccess(response -> logger.verbose("Retrieved the next deleted secrets page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next deleted secrets page - Page {}", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<DeletedSecret>> listDeletedSecretsFirstPage(Context context) { try { return service.getDeletedSecretsAsync(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Listing deleted secrets")) .doOnSuccess(response -> logger.verbose("Listed deleted secrets")) .doOnError(error -> logger.warning("Failed to list deleted secrets", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } public PagedFlux<SecretProperties> listPropertiesOfSecretVersionsAsync(String name) { try { return new PagedFlux<>( () -> withContext(context -> listSecretVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listSecretVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } public PagedFlux<SecretProperties> listPropertiesOfSecretVersionsAsync(String name, Context context) { return new PagedFlux<>( () -> listSecretVersionsFirstPage(name, context), continuationToken -> listSecretVersionsNextPage(continuationToken, context)); } /* * Gets attributes of all the secrets versions given by the {@code nextPageLink} that was retrieved from a call to * {@link SecretAsyncClient * * @param continuationToken The {@link PagedResponse * list operations. * * @return A {@link Mono} of {@link PagedResponse<SecretProperties>} from the next page of results. */ private Mono<PagedResponse<SecretProperties>> listSecretVersionsNextPage(String continuationToken, Context context) { try { return service.getSecretsAsync(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving the next secrets versions page - Page {}", continuationToken)) .doOnSuccess(response -> logger.verbose("Retrieved the next secrets versions page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next secrets versions page - Page {}", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /* * Calls the service and retrieve first page result. It makes one call and retrieve {@code * DEFAULT_MAX_PAGE_RESULTS} values. */ private Mono<PagedResponse<SecretProperties>> listSecretVersionsFirstPage(String name, Context context) { try { return service.getSecretVersionsAsync(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Listing secret versions - {}", name)) .doOnSuccess(response -> logger.verbose("Listed secret versions - {}", name)) .doOnError(error -> logger.warning("Failed to list secret versions - {}", name, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Context enableSyncRestProxy(Context context) { return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true); } }
class SecretClientImpl { static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1); private final String vaultUrl; private final SecretService service; private final ClientLogger logger = new ClientLogger(SecretClientImpl.class); private final HttpPipeline pipeline; private final SecretServiceVersion secretServiceVersion; /** * Creates a {@link SecretClientImpl} that uses an {@link HttpPipeline} to service requests. * * @param vaultUrl URL for the Azure KeyVault service. * @param pipeline {@link HttpPipeline} that the HTTP requests and responses flow through. * @param secretServiceVersion {@link SecretServiceVersion} of the service to be used when making requests. */ public SecretClientImpl(String vaultUrl, HttpPipeline pipeline, SecretServiceVersion secretServiceVersion) { Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.vaultUrl = vaultUrl; this.service = RestProxy.create(SecretService.class, pipeline); this.pipeline = pipeline; this.secretServiceVersion = secretServiceVersion; } /** * Gets the vault endpoint URL to which service requests are sent to. * * @return The vault endpoint URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The {@link HttpPipeline pipeline}. */ public HttpPipeline getHttpPipeline() { return this.pipeline; } /** * Gets the default polling interval for long running operations. * * @return The default polling interval for long running operations */ public Duration getDefaultPollingInterval() { return DEFAULT_POLLING_INTERVAL; } /** * The interface defining all the services for {@link SecretClientImpl} to be used by the proxy service to perform * REST calls. * * This is package-private so that these REST calls are transparent to the user. */ @Host("{url}") @ServiceInterface(name = "KeyVault") public interface SecretService { @Put("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> setSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Put("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> setSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> getSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> getSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> getSecretPollerAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(code = {403}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> getSecretPoller(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Patch("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<SecretProperties>> updateSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Patch("secrets/{secret-name}/{secret-version}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<SecretProperties> updateSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Delete("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<DeletedSecret>> deleteSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Delete("secrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<DeletedSecret> deleteSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<DeletedSecret>> getDeletedSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<DeletedSecret> getDeletedSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<DeletedSecret>> getDeletedSecretPollerAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets/{secret-name}") @ExpectedResponses({200, 404}) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<DeletedSecret> getDeletedSecretPoller(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Delete("deletedsecrets/{secret-name}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<Void>> purgeDeletedSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Delete("deletedsecrets/{secret-name}") @ExpectedResponses({204}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<Void> purgeDeletedSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("deletedsecrets/{secret-name}/recover") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> recoverDeletedSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("deletedsecrets/{secret-name}/recover") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> recoverDeletedSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/{secret-name}/backup") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<SecretBackup>> backupSecretAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/{secret-name}/backup") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {404}, value = ResourceNotFoundException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<SecretBackup> backupSecret(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/restore") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Mono<Response<KeyVaultSecret>> restoreSecretAsync(@HostParam("url") String url, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRestoreRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Post("secrets/restore") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(code = {400}, value = ResourceModifiedException.class) @UnexpectedResponseExceptionType(HttpResponseException.class) Response<KeyVaultSecret> restoreSecret(@HostParam("url") String url, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @BodyParam("application/json") SecretRestoreRequestParameters parameters, @HeaderParam("Content-Type") String type, Context context); @Get("secrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) Mono<PagedResponse<SecretProperties>> getSecretsAsync(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) PagedResponse<SecretProperties> getSecrets(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/versions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) Mono<PagedResponse<SecretProperties>> getSecretVersionsAsync(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("secrets/{secret-name}/versions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) PagedResponse<SecretProperties> getSecretVersions(@HostParam("url") String url, @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) Mono<PagedResponse<SecretProperties>> getSecretsAsync(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(SecretPropertiesPage.class) PagedResponse<SecretProperties> getSecrets(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) Mono<PagedResponse<DeletedSecret>> getDeletedSecretsAsync(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("deletedsecrets") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) PagedResponse<DeletedSecret> getDeletedSecrets(@HostParam("url") String url, @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) Mono<PagedResponse<DeletedSecret>> getDeletedSecretsAsync(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); @Get("{nextUrl}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(HttpResponseException.class) @ReturnValueWireType(DeletedSecretPage.class) PagedResponse<DeletedSecret> getDeletedSecrets(@HostParam("url") String url, @PathParam(value = "nextUrl", encoded = true) String nextUrl, @HeaderParam("accept-language") String acceptLanguage, @HeaderParam("Content-Type") String type, Context context); } public Mono<Response<KeyVaultSecret>> setSecretWithResponseAsync(KeyVaultSecret secret, Context context) { SecretRequestParameters parameters = validateAndCreateSetSecretParameters(secret); return service.setSecretAsync(vaultUrl, secret.getName(), secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.verbose("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } public Response<KeyVaultSecret> setSecretWithResponse(KeyVaultSecret secret, Context context) { SecretRequestParameters parameters = validateAndCreateSetSecretParameters(secret); context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.setSecret(vaultUrl, secret.getName(), secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } private SecretRequestParameters validateAndCreateSetSecretParameters(KeyVaultSecret secret) { Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); return new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); } public Mono<Response<KeyVaultSecret>> setSecretWithResponseAsync(String name, String value, Context context) { SecretRequestParameters parameters = new SecretRequestParameters().setValue(value); return service.setSecretAsync(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Setting secret - {}", name)) .doOnSuccess(response -> logger.verbose("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", name, error)); } public Response<KeyVaultSecret> setSecretWithResponse(String name, String value, Context context) { SecretRequestParameters parameters = new SecretRequestParameters().setValue(value); context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.setSecret(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public Mono<Response<KeyVaultSecret>> getSecretWithResponseAsync(String name, String version, Context context) { return service.getSecretAsync(vaultUrl, name, version == null ? "" : version, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving secret - {}", name)) .doOnSuccess(response -> logger.verbose("Retrieved secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to get secret - {}", name, error)); } public Mono<Response<SecretProperties>> updateSecretPropertiesWithResponseAsync(SecretProperties secretProperties, Context context) { SecretRequestParameters parameters = validateAndCreateUpdateSecretRequestParameters(secretProperties); return service.updateSecretAsync(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Updating secret - {}", secretProperties.getName())) .doOnSuccess(response -> logger.verbose("Updated secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update secret - {}", secretProperties.getName(), error)); } public Response<SecretProperties> updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { SecretRequestParameters parameters = validateAndCreateUpdateSecretRequestParameters(secretProperties); context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.updateSecret(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } private SecretRequestParameters validateAndCreateUpdateSecretRequestParameters(SecretProperties secretProperties) { Objects.requireNonNull(secretProperties, "The secret properties input parameter cannot be null."); return new SecretRequestParameters() .setTags(secretProperties.getTags()) .setContentType(secretProperties.getContentType()) .setSecretAttributes(new SecretRequestAttributes(secretProperties)); } public PollerFlux<DeletedSecret, Void> beginDeleteSecretAsync(String name) { return new PollerFlux<>(getDefaultPollingInterval(), activationOperation(name), createPollOperation(name), (pollingContext, firstResponse) -> Mono.empty(), (pollingContext) -> Mono.empty()); } private Function<PollingContext<DeletedSecret>, Mono<DeletedSecret>> activationOperation(String name) { return (pollingContext) -> withContext(context -> deleteSecretWithResponseAsync(name, context)). flatMap(deletedSecretResponse -> Mono.just(deletedSecretResponse.getValue())); } /** * Polling operation to poll on the delete secret operation status. */ private Function<PollingContext<DeletedSecret>, Mono<PollResponse<DeletedSecret>>> createPollOperation(String keyName) { return pollingContext -> withContext(context -> service.getDeletedSecretPollerAsync(vaultUrl, keyName, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(deletedSecretResponse -> { if (deletedSecretResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedSecretResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } private Mono<Response<DeletedSecret>> deleteSecretWithResponseAsync(String name, Context context) { return service.deleteSecretAsync(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Deleting secret - {}", name)) .doOnSuccess(response -> logger.verbose("Deleted secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to delete secret - {}", name, error)); } public Mono<Response<DeletedSecret>> getDeletedSecretWithResponseAsync(String name, Context context) { return service.getDeletedSecretAsync(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Retrieving deleted secret - {}", name)) .doOnSuccess(response -> logger.verbose("Retrieved deleted secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to retrieve deleted secret - {}", name, error)); } public Response<DeletedSecret> getDeletedSecretWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.getDeletedSecret(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public Mono<Response<Void>> purgeDeletedSecretWithResponseAsync(String name, Context context) { return service.purgeDeletedSecretAsync(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Purging deleted secret - {}", name)) .doOnSuccess(response -> logger.verbose("Purged deleted secret - {}", name)) .doOnError(error -> logger.warning("Failed to purge deleted secret - {}", name, error)); } public Response<Void> purgeDeletedSecretWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.purgeDeletedSecret(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public PollerFlux<KeyVaultSecret, Void> beginRecoverDeletedSecretAsync(String name) { return new PollerFlux<>(getDefaultPollingInterval(), recoverActivationOperation(name), createRecoverPollOperation(name), (pollerContext, firstResponse) -> Mono.empty(), (pollingContext) -> Mono.empty()); } private Function<PollingContext<KeyVaultSecret>, Mono<KeyVaultSecret>> recoverActivationOperation(String name) { return (pollingContext) -> withContext(context -> recoverDeletedSecretWithResponseAsync(name, context)).flatMap(keyResponse -> Mono.just(keyResponse.getValue())); } /* * Polling operation to poll on the recover deleted secret operation status. */ private Function<PollingContext<KeyVaultSecret>, Mono<PollResponse<KeyVaultSecret>>> createRecoverPollOperation(String secretName) { return pollingContext -> withContext(context -> service.getSecretPollerAsync(vaultUrl, secretName, "", secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))) .flatMap(secretResponse -> { if (secretResponse.getStatusCode() == 404) { return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()))); } return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, secretResponse.getValue()))); }) .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue())); } private Mono<Response<KeyVaultSecret>> recoverDeletedSecretWithResponseAsync(String name, Context context) { return service.recoverDeletedSecretAsync(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Recovering deleted secret - {}", name)) .doOnSuccess(response -> logger.verbose("Recovered deleted secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to recover deleted secret - {}", name, error)); } public Mono<Response<byte[]>> backupSecretWithResponseAsync(String name, Context context) { return service.backupSecretAsync(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Backing up secret - {}", name)) .doOnSuccess(response -> logger.verbose("Backed up secret - {}", name)) .doOnError(error -> logger.warning("Failed to back up secret - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse<>(base64URLResponse.getRequest(), base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue()))); } public Response<byte[]> backupSecretWithResponse(String name, Context context) { context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); Response<SecretBackup> secretBackupResponse = service. backupSecret(vaultUrl, name, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); return new SimpleResponse<>(secretBackupResponse.getRequest(), secretBackupResponse.getStatusCode(), secretBackupResponse.getHeaders(), secretBackupResponse.getValue().getValue()); } public Mono<Response<KeyVaultSecret>> restoreSecretBackupWithResponseAsync(byte[] backup, Context context) { SecretRestoreRequestParameters parameters = new SecretRestoreRequestParameters().setSecretBackup(backup); return service.restoreSecretAsync(vaultUrl, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Attempting to restore secret")) .doOnSuccess(response -> logger.verbose("Restored secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to restore secret", error)); } public Response<KeyVaultSecret> restoreSecretBackupWithResponse(byte[] backup, Context context) { SecretRestoreRequestParameters parameters = new SecretRestoreRequestParameters().setSecretBackup(backup); context = context == null ? Context.NONE : context; context = enableSyncRestProxy(context); return service.restoreSecret(vaultUrl, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)); } public PagedFlux<SecretProperties> listPropertiesOfSecrets() { try { return new PagedFlux<>( () -> withContext(this::listSecretsFirstPage), continuationToken -> withContext(context -> listSecretsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } public PagedFlux<SecretProperties> listPropertiesOfSecrets(Context context) { return new PagedFlux<>( () -> listSecretsFirstPage(context), continuationToken -> listSecretsNextPage(continuationToken, context)); } /** * Gets attributes of the first 25 secrets that can be found on a given key vault. * * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service * call. * * @return A {@link Mono} of {@link PagedResponse} containing {@link SecretProperties} instances from the next page * of results. */ private Mono<PagedResponse<SecretProperties>> listSecretsFirstPage(Context context) { try { return service.getSecretsAsync(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Listing secrets")) .doOnSuccess(response -> logger.verbose("Listed secrets")) .doOnError(error -> logger.warning("Failed to list secrets", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to * {@link SecretClientImpl * * @param continuationToken The {@link PagedResponse * of the list operations. * * @return A {@link Mono} of {@link PagedResponse} containing {@link SecretProperties} instances from the next page * of results. */ private Mono<PagedResponse<SecretProperties>> listSecretsNextPage(String continuationToken, Context context) { try { return service.getSecretsAsync(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving the next secrets page - Page {}", continuationToken)) .doOnSuccess(response -> logger.verbose("Retrieved the next secrets page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next secrets page - Page {}", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } public PagedFlux<DeletedSecret> listDeletedSecrets() { try { return new PagedFlux<>( () -> withContext(this::listDeletedSecretsFirstPage), continuationToken -> withContext(context -> listDeletedSecretsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } public PagedFlux<DeletedSecret> listDeletedSecrets(Context context) { return new PagedFlux<>( () -> listDeletedSecretsFirstPage(context), continuationToken -> listDeletedSecretsNextPage(continuationToken, context)); } /** * Gets attributes of the first 25 deleted secrets that can be found on a given key vault. * * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service * call. * * @return A {@link Mono} of {@link PagedResponse} containing {@link SecretProperties} instances from the next page * of results. */ private Mono<PagedResponse<DeletedSecret>> listDeletedSecretsFirstPage(Context context) { try { return service.getDeletedSecretsAsync(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Listing deleted secrets")) .doOnSuccess(response -> logger.verbose("Listed deleted secrets")) .doOnError(error -> logger.warning("Failed to list deleted secrets", error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to * {@link SecretClientImpl * * @param continuationToken The {@link Page * list operations. * * @return A {@link Mono} of {@link PagedResponse} that contains {@link DeletedSecret} from the next page of * results. */ private Mono<PagedResponse<DeletedSecret>> listDeletedSecretsNextPage(String continuationToken, Context context) { try { return service.getDeletedSecretsAsync(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving the next deleted secrets page - Page {}", continuationToken)) .doOnSuccess(response -> logger.verbose("Retrieved the next deleted secrets page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next deleted secrets page - Page {}", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } public PagedFlux<SecretProperties> listPropertiesOfSecretVersions(String name) { try { return new PagedFlux<>( () -> withContext(context -> listSecretVersionsFirstPage(name, context)), continuationToken -> withContext(context -> listSecretVersionsNextPage(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } public PagedFlux<SecretProperties> listPropertiesOfSecretVersions(String name, Context context) { return new PagedFlux<>( () -> listSecretVersionsFirstPage(name, context), continuationToken -> listSecretVersionsNextPage(continuationToken, context)); } /** * Gets attributes of the first 25 versions of a secret. * * @param context Additional {@link Context} that is passed through the {@link HttpPipeline} during the service * call. * * @return A {@link Mono} of {@link PagedResponse} containing {@link SecretProperties} instances from the next page * of results. */ private Mono<PagedResponse<SecretProperties>> listSecretVersionsFirstPage(String name, Context context) { try { return service.getSecretVersionsAsync(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, secretServiceVersion.getVersion(), ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignored -> logger.verbose("Listing secret versions - {}", name)) .doOnSuccess(response -> logger.verbose("Listed secret versions - {}", name)) .doOnError(error -> logger.warning("Failed to list secret versions - {}", name, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets attributes of versions of a key given by the {@code nextPageLink} that was retrieved from a call to * {@link SecretClientImpl * * @param continuationToken The {@link PagedResponse * of the list operations. * * @return A {@link Mono} of {@link PagedResponse} containing {@link SecretProperties} instances from the next page * of results. */ private Mono<PagedResponse<SecretProperties>> listSecretVersionsNextPage(String continuationToken, Context context) { try { return service.getSecretsAsync(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)) .doOnRequest(ignoredValue -> logger.verbose("Retrieving the next secrets versions page - Page {}", continuationToken)) .doOnSuccess(response -> logger.verbose("Retrieved the next secrets versions page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next secrets versions page - Page {}", continuationToken, error)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Context enableSyncRestProxy(Context context) { return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true); } }
as discussed offline, let's make it instance level cache.
public SwaggerMethodParser getMethodParser(Method swaggerMethod) { return METHOD_PARSERS.computeIfAbsent(swaggerMethod, sm -> new SwaggerMethodParser(this, sm, getHost())); }
return METHOD_PARSERS.computeIfAbsent(swaggerMethod, sm -> new SwaggerMethodParser(this, sm, getHost()));
public SwaggerMethodParser getMethodParser(Method swaggerMethod) { return methodParsers.computeIfAbsent(swaggerMethod, sm -> new SwaggerMethodParser(this, sm)); }
class SwaggerInterfaceParser { private final String host; private final String serviceName; private static final Map<Method, SwaggerMethodParser> METHOD_PARSERS = new ConcurrentHashMap<>(); /** * Create a SwaggerInterfaceParser object with the provided fully qualified interface name. * * @param swaggerInterface The interface that will be parsed. */ public SwaggerInterfaceParser(Class<?> swaggerInterface) { final Host hostAnnotation = swaggerInterface.getAnnotation(Host.class); if (hostAnnotation != null && !hostAnnotation.value().isEmpty()) { this.host = hostAnnotation.value(); } else { throw new MissingRequiredAnnotationException(Host.class, swaggerInterface); } ServiceInterface serviceAnnotation = swaggerInterface.getAnnotation(ServiceInterface.class); if (serviceAnnotation != null && !serviceAnnotation.name().isEmpty()) { serviceName = serviceAnnotation.name(); } else { throw new MissingRequiredAnnotationException(ServiceInterface.class, swaggerInterface); } } /** * Get the method parser that is associated with the provided swaggerMethod. The method parser can be used to get * details about the Swagger REST API call. * * @param swaggerMethod the method to generate a parser for * @return the SwaggerMethodParser associated with the provided swaggerMethod */ /** * Get the desired host that the provided Swagger interface will target with its REST API calls. This value is * retrieved from the @Host annotation placed on the Swagger interface. * * @return The value of the @Host annotation. */ public String getHost() { return host; } public String getServiceName() { return serviceName; } }
class SwaggerInterfaceParser { private static final Map<Class<?>, SwaggerInterfaceParser> INTERFACE_PARSERS = new ConcurrentHashMap<>(); private final String host; private final String serviceName; private final Map<Method, SwaggerMethodParser> methodParsers = new ConcurrentHashMap<>(); /** * Create a SwaggerInterfaceParser object with the provided fully qualified interface name. * * @param swaggerInterface The interface that will be parsed. * @return The {@link SwaggerInterfaceParser} for the passed interface. */ public static SwaggerInterfaceParser getInstance(Class<?> swaggerInterface) { if (INTERFACE_PARSERS.size() >= MAX_CACHE_SIZE) { INTERFACE_PARSERS.clear(); } return INTERFACE_PARSERS.computeIfAbsent(swaggerInterface, SwaggerInterfaceParser::new); } private SwaggerInterfaceParser(Class<?> swaggerInterface) { final Host hostAnnotation = swaggerInterface.getAnnotation(Host.class); if (hostAnnotation != null && !hostAnnotation.value().isEmpty()) { this.host = hostAnnotation.value(); } else { throw new MissingRequiredAnnotationException(Host.class, swaggerInterface); } ServiceInterface serviceAnnotation = swaggerInterface.getAnnotation(ServiceInterface.class); if (serviceAnnotation != null && !serviceAnnotation.name().isEmpty()) { serviceName = serviceAnnotation.name(); } else { throw new MissingRequiredAnnotationException(ServiceInterface.class, swaggerInterface); } } /** * Get the method parser that is associated with the provided swaggerMethod. The method parser can be used to get * details about the Swagger REST API call. * * @param swaggerMethod the method to generate a parser for * @return the SwaggerMethodParser associated with the provided swaggerMethod */ /** * Get the desired host that the provided Swagger interface will target with its REST API calls. This value is * retrieved from the @Host annotation placed on the Swagger interface. * * @return The value of the @Host annotation. */ public String getHost() { return host; } public String getServiceName() { return serviceName; } }
is it possible to avoid KeyAsyncClient creation here? I'd assume that what we need is the impl client? See https://github.com/Azure/azure-sdk-for-java/blob/3c92d218de218b2fe8b0bcc39e2a653f4f1a59d1/sdk/anomalydetector/azure-ai-anomalydetector/src/main/java/com/azure/ai/anomalydetector/AnomalyDetectorClientBuilder.java#L239-L250
public KeyClient buildClient() { KeyAsyncClient asyncClient = buildAsyncClient(); KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); return new KeyClient(asyncClient.getVaultUrl(), asyncClient.getHttpPipeline(), serviceVersion); }
return new KeyClient(asyncClient.getVaultUrl(), asyncClient.getHttpPipeline(), serviceVersion);
public KeyClient buildClient() { return new KeyClient(buildInnerClient()); }
class KeyClientBuilder implements TokenCredentialTrait<KeyClientBuilder>, HttpTrait<KeyClientBuilder>, ConfigurationTrait<KeyClientBuilder> { private final ClientLogger logger = new ClientLogger(KeyClientBuilder.class); private static final String AZURE_KEY_VAULT_KEYS = "azure-key-vault-keys.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private TokenCredential credential; private HttpPipeline pipeline; private URL vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private Configuration configuration; private KeyServiceVersion version; private ClientOptions clientOptions; /** * The constructor with defaults. */ public KeyClientBuilder() { httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_KEYS); } /** * Creates a {@link KeyClient} based on options set in the builder. * Every time {@code buildClient()} is called, a new instance of {@link KeyClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * KeyClientBuilder * * @return A {@link KeyClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ /** * Creates a {@link KeyAsyncClient} based on options set in the builder. * Every time {@code buildAsyncClient()} is called, a new instance of {@link KeyAsyncClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * key vault url are required to build the {@link KeyAsyncClient client}.</p> * * @return A {@link KeyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ public KeyAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); if (pipeline != null) { return new KeyAsyncClient(vaultUrl, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError( new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.CREDENTIAL_REQUIRED))); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyAsyncClient(vaultUrl, pipeline, serviceVersion); } /** * Sets the vault endpoint URL to send HTTP requests to. * * @param vaultUrl The vault url is used as destination on Azure to send requests to. If you have a key identifier, * create a new {@link KeyVaultKeyIdentifier} to parse it and obtain the {@code vaultUrl} and other * information. * * @return The updated {@link KeyClientBuilder} object. * * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyClientBuilder vaultUrl(String vaultUrl) { if (vaultUrl == null) { throw logger.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); } try { this.vaultUrl = new URL(vaultUrl); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalArgumentException( "The Azure Key Vault url is malformed.", ex)); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public KeyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ @Override public KeyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@code pipeline} is set. * * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Sets the {@link KeyServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link KeyServiceVersion} of the service to be used when making requests. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder serviceVersion(KeyServiceVersion version) { this.version = version; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used in the pipeline, if not provided. * * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private URL getBuildEndpoint(Configuration configuration) { if (vaultUrl != null) { return vaultUrl; } String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); if (CoreUtils.isNullOrEmpty(configEndpoint)) { return null; } try { return new URL(configEndpoint); } catch (MalformedURLException ex) { return null; } } }
class KeyClientBuilder implements TokenCredentialTrait<KeyClientBuilder>, HttpTrait<KeyClientBuilder>, ConfigurationTrait<KeyClientBuilder> { private final ClientLogger logger = new ClientLogger(KeyClientBuilder.class); private static final String AZURE_KEY_VAULT_KEYS = "azure-key-vault-keys.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private TokenCredential credential; private HttpPipeline pipeline; private String vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private Configuration configuration; private KeyServiceVersion version; private ClientOptions clientOptions; /** * The constructor with defaults. */ public KeyClientBuilder() { httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_KEYS); } /** * Creates a {@link KeyClient} based on options set in the builder. * Every time {@code buildClient()} is called, a new instance of {@link KeyClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * KeyClientBuilder * * @return A {@link KeyClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ /** * Creates a {@link KeyAsyncClient} based on options set in the builder. * Every time {@code buildAsyncClient()} is called, a new instance of {@link KeyAsyncClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * key vault url are required to build the {@link KeyAsyncClient client}.</p> * * @return A {@link KeyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ public KeyAsyncClient buildAsyncClient() { return new KeyAsyncClient(buildInnerClient()); } private KeyClientImpl buildInnerClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; String buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); if (pipeline != null) { return new KeyClientImpl(vaultUrl, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError( new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.CREDENTIAL_REQUIRED))); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyClientImpl(vaultUrl, pipeline, serviceVersion); } /** * Sets the vault endpoint URL to send HTTP requests to. * * @param vaultUrl The vault url is used as destination on Azure to send requests to. If you have a key identifier, * create a new {@link KeyVaultKeyIdentifier} to parse it and obtain the {@code vaultUrl} and other * information. * * @return The updated {@link KeyClientBuilder} object. * * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyClientBuilder vaultUrl(String vaultUrl) { if (vaultUrl == null) { throw logger.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); } try { URL url = new URL(vaultUrl); this.vaultUrl = url.toString(); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalArgumentException( "The Azure Key Vault url is malformed.", ex)); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public KeyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ @Override public KeyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@code pipeline} is set. * * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Sets the {@link KeyServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link KeyServiceVersion} of the service to be used when making requests. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder serviceVersion(KeyServiceVersion version) { this.version = version; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used in the pipeline, if not provided. * * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private String getBuildEndpoint(Configuration configuration) { if (vaultUrl != null) { return vaultUrl; } String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); if (CoreUtils.isNullOrEmpty(configEndpoint)) { return null; } try { URL url = new URL(configEndpoint); return url.toString(); } catch (MalformedURLException ex) { return null; } } }
Given the change to using `String` instead of `URL` should the property in the class be changed to `String` so it doesn't need to be converted back to a String when built.
private KeyClientImpl buildInnerClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); if (pipeline != null) { return new KeyClientImpl(vaultUrl.toString(), pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError( new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.CREDENTIAL_REQUIRED))); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyClientImpl(vaultUrl.toString(), pipeline, serviceVersion); }
return new KeyClientImpl(vaultUrl.toString(), pipeline, serviceVersion);
private KeyClientImpl buildInnerClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; String buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); if (pipeline != null) { return new KeyClientImpl(vaultUrl, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError( new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.CREDENTIAL_REQUIRED))); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(clientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration)); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyClientImpl(vaultUrl, pipeline, serviceVersion); }
class KeyClientBuilder implements TokenCredentialTrait<KeyClientBuilder>, HttpTrait<KeyClientBuilder>, ConfigurationTrait<KeyClientBuilder> { private final ClientLogger logger = new ClientLogger(KeyClientBuilder.class); private static final String AZURE_KEY_VAULT_KEYS = "azure-key-vault-keys.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private TokenCredential credential; private HttpPipeline pipeline; private URL vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private Configuration configuration; private KeyServiceVersion version; private ClientOptions clientOptions; /** * The constructor with defaults. */ public KeyClientBuilder() { httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_KEYS); } /** * Creates a {@link KeyClient} based on options set in the builder. * Every time {@code buildClient()} is called, a new instance of {@link KeyClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * KeyClientBuilder * * @return A {@link KeyClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ public KeyClient buildClient() { return new KeyClient(buildInnerClient()); } /** * Creates a {@link KeyAsyncClient} based on options set in the builder. * Every time {@code buildAsyncClient()} is called, a new instance of {@link KeyAsyncClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * key vault url are required to build the {@link KeyAsyncClient client}.</p> * * @return A {@link KeyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ public KeyAsyncClient buildAsyncClient() { return new KeyAsyncClient(buildInnerClient()); } /** * Sets the vault endpoint URL to send HTTP requests to. * * @param vaultUrl The vault url is used as destination on Azure to send requests to. If you have a key identifier, * create a new {@link KeyVaultKeyIdentifier} to parse it and obtain the {@code vaultUrl} and other * information. * * @return The updated {@link KeyClientBuilder} object. * * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyClientBuilder vaultUrl(String vaultUrl) { if (vaultUrl == null) { throw logger.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); } try { this.vaultUrl = new URL(vaultUrl); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalArgumentException( "The Azure Key Vault url is malformed.", ex)); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public KeyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ @Override public KeyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@code pipeline} is set. * * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Sets the {@link KeyServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link KeyServiceVersion} of the service to be used when making requests. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder serviceVersion(KeyServiceVersion version) { this.version = version; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used in the pipeline, if not provided. * * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private URL getBuildEndpoint(Configuration configuration) { if (vaultUrl != null) { return vaultUrl; } String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); if (CoreUtils.isNullOrEmpty(configEndpoint)) { return null; } try { return new URL(configEndpoint); } catch (MalformedURLException ex) { return null; } } }
class KeyClientBuilder implements TokenCredentialTrait<KeyClientBuilder>, HttpTrait<KeyClientBuilder>, ConfigurationTrait<KeyClientBuilder> { private final ClientLogger logger = new ClientLogger(KeyClientBuilder.class); private static final String AZURE_KEY_VAULT_KEYS = "azure-key-vault-keys.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final List<HttpPipelinePolicy> perCallPolicies; private final List<HttpPipelinePolicy> perRetryPolicies; private final Map<String, String> properties; private TokenCredential credential; private HttpPipeline pipeline; private String vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private Configuration configuration; private KeyServiceVersion version; private ClientOptions clientOptions; /** * The constructor with defaults. */ public KeyClientBuilder() { httpLogOptions = new HttpLogOptions(); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); properties = CoreUtils.getProperties(AZURE_KEY_VAULT_KEYS); } /** * Creates a {@link KeyClient} based on options set in the builder. * Every time {@code buildClient()} is called, a new instance of {@link KeyClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * KeyClientBuilder * * @return A {@link KeyClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ public KeyClient buildClient() { return new KeyClient(buildInnerClient()); } /** * Creates a {@link KeyAsyncClient} based on options set in the builder. * Every time {@code buildAsyncClient()} is called, a new instance of {@link KeyAsyncClient} is created. * * <p>If {@link KeyClientBuilder * {@link KeyClientBuilder * All other builder settings are ignored. If {@code pipeline} is not set, then {@link * KeyClientBuilder * key vault url are required to build the {@link KeyAsyncClient client}.</p> * * @return A {@link KeyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyClientBuilder * {@link KeyClientBuilder * @throws IllegalStateException If both {@link * and {@link */ public KeyAsyncClient buildAsyncClient() { return new KeyAsyncClient(buildInnerClient()); } /** * Sets the vault endpoint URL to send HTTP requests to. * * @param vaultUrl The vault url is used as destination on Azure to send requests to. If you have a key identifier, * create a new {@link KeyVaultKeyIdentifier} to parse it and obtain the {@code vaultUrl} and other * information. * * @return The updated {@link KeyClientBuilder} object. * * @throws IllegalArgumentException If {@code vaultUrl} cannot be parsed into a valid URL. * @throws NullPointerException If {@code vaultUrl} is {@code null}. */ public KeyClientBuilder vaultUrl(String vaultUrl) { if (vaultUrl == null) { throw logger.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); } try { URL url = new URL(vaultUrl); this.vaultUrl = url.toString(); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalArgumentException( "The Azure Key Vault url is malformed.", ex)); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public KeyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } this.credential = credential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link KeyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ @Override public KeyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * {@code pipeline} is set. * * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Sets the {@link KeyServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link KeyServiceVersion} of the service to be used when making requests. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder serviceVersion(KeyServiceVersion version) { this.version = version; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used in the pipeline, if not provided. * * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * * @return The updated {@link KeyClientBuilder} object. */ public KeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return The updated {@link KeyClientBuilder} object. */ @Override public KeyClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private String getBuildEndpoint(Configuration configuration) { if (vaultUrl != null) { return vaultUrl; } String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); if (CoreUtils.isNullOrEmpty(configEndpoint)) { return null; } try { URL url = new URL(configEndpoint); return url.toString(); } catch (MalformedURLException ex) { return null; } } }
why commented out?
public Mono<Boolean> isInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(markerDocId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); return this.client.readItem(markerDocId, new PartitionKey(markerDocId), requestOptions, InternalObjectNode.class) .flatMap(documentResourceResponse -> Mono.just(BridgeInternal.getProperties(documentResourceResponse) != null)) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isNotFound(e)) { return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); }
public Mono<Boolean> isInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(markerDocId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); return this.client.readItem(markerDocId, new PartitionKey(markerDocId), requestOptions, InternalObjectNode.class) .flatMap(documentResourceResponse -> Mono.just(BridgeInternal.getProperties(documentResourceResponse) != null)) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isNotFound(e)) { logger.info("Lease synchronization document not found"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); }
class DocumentServiceLeaseStore implements LeaseStore { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private ChangeFeedContextClient client; private String containerNamePrefix; private CosmosAsyncContainer leaseCollectionLink; private RequestOptionsFactory requestOptionsFactory; private volatile String lockETag; public DocumentServiceLeaseStore( ChangeFeedContextClient client, String containerNamePrefix, CosmosAsyncContainer leaseCollectionLink, RequestOptionsFactory requestOptionsFactory) { this.client = client; this.containerNamePrefix = containerNamePrefix; this.leaseCollectionLink = leaseCollectionLink; this.requestOptionsFactory = requestOptionsFactory; } @Override @Override public Mono<Boolean> markInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map( item -> { return true; }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isConflict(e)) { return Mono.just(true); } } return Mono.just(false); }); } @Override public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(lockId); BridgeInternal.setProperty(containerDocument, Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map(documentResourceResponse -> { if (BridgeInternal.getProperties(documentResourceResponse) != null) { this.lockETag = BridgeInternal.getProperties(documentResourceResponse).getETag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } @Override public Mono<Boolean> releaseInitializationLock() { String lockId = this.getStoreLockName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(lockId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } requestOptions.setIfMatchETag(this.lockETag); return this.client.deleteItem(lockId, new PartitionKey(lockId), requestOptions) .map(documentResourceResponse -> { if (documentResourceResponse.getItem() != null) { this.lockETag = null; return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } private String getStoreMarkerName() { return this.containerNamePrefix + ".info"; } private String getStoreLockName() { return this.containerNamePrefix + ".lock"; } }
class DocumentServiceLeaseStore implements LeaseStore { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final ChangeFeedContextClient client; private final String containerNamePrefix; private final CosmosAsyncContainer leaseCollectionLink; private final RequestOptionsFactory requestOptionsFactory; private volatile String lockETag; public DocumentServiceLeaseStore( ChangeFeedContextClient client, String containerNamePrefix, CosmosAsyncContainer leaseCollectionLink, RequestOptionsFactory requestOptionsFactory) { this.client = client; this.containerNamePrefix = containerNamePrefix; this.leaseCollectionLink = leaseCollectionLink; this.requestOptionsFactory = requestOptionsFactory; } @Override @Override public Mono<Boolean> markInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map( item -> { return true; }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isConflict(e)) { logger.info("Lease synchronization document was created by a different instance"); return Mono.just(true); } } logger.error("Unexpected exception thrown", throwable); return Mono.just(false); }); } @Override public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(lockId); BridgeInternal.setProperty(containerDocument, Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map(documentResourceResponse -> { if (BridgeInternal.getProperties(documentResourceResponse) != null) { this.lockETag = BridgeInternal.getProperties(documentResourceResponse).getETag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } @Override public Mono<Boolean> releaseInitializationLock() { String lockId = this.getStoreLockName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(lockId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } requestOptions.setIfMatchETag(this.lockETag); return this.client.deleteItem(lockId, new PartitionKey(lockId), requestOptions) .map(documentResourceResponse -> { if (documentResourceResponse.getItem() != null) { this.lockETag = null; return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } private String getStoreMarkerName() { return this.containerNamePrefix + ".info"; } private String getStoreLockName() { return this.containerNamePrefix + ".lock"; } }
nit: do we need to keep the commented code?
public Mono<Boolean> markInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map( item -> { return true; }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isConflict(e)) { return Mono.just(true); } } return Mono.just(false); }); }
public Mono<Boolean> markInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map( item -> { return true; }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isConflict(e)) { logger.info("Lease synchronization document was created by a different instance"); return Mono.just(true); } } logger.error("Unexpected exception thrown", throwable); return Mono.just(false); }); }
class DocumentServiceLeaseStore implements LeaseStore { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private ChangeFeedContextClient client; private String containerNamePrefix; private CosmosAsyncContainer leaseCollectionLink; private RequestOptionsFactory requestOptionsFactory; private volatile String lockETag; public DocumentServiceLeaseStore( ChangeFeedContextClient client, String containerNamePrefix, CosmosAsyncContainer leaseCollectionLink, RequestOptionsFactory requestOptionsFactory) { this.client = client; this.containerNamePrefix = containerNamePrefix; this.leaseCollectionLink = leaseCollectionLink; this.requestOptionsFactory = requestOptionsFactory; } @Override public Mono<Boolean> isInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(markerDocId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); return this.client.readItem(markerDocId, new PartitionKey(markerDocId), requestOptions, InternalObjectNode.class) .flatMap(documentResourceResponse -> Mono.just(BridgeInternal.getProperties(documentResourceResponse) != null)) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isNotFound(e)) { return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } @Override @Override public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(lockId); BridgeInternal.setProperty(containerDocument, Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map(documentResourceResponse -> { if (BridgeInternal.getProperties(documentResourceResponse) != null) { this.lockETag = BridgeInternal.getProperties(documentResourceResponse).getETag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } @Override public Mono<Boolean> releaseInitializationLock() { String lockId = this.getStoreLockName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(lockId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } requestOptions.setIfMatchETag(this.lockETag); return this.client.deleteItem(lockId, new PartitionKey(lockId), requestOptions) .map(documentResourceResponse -> { if (documentResourceResponse.getItem() != null) { this.lockETag = null; return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } private String getStoreMarkerName() { return this.containerNamePrefix + ".info"; } private String getStoreLockName() { return this.containerNamePrefix + ".lock"; } }
class DocumentServiceLeaseStore implements LeaseStore { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final ChangeFeedContextClient client; private final String containerNamePrefix; private final CosmosAsyncContainer leaseCollectionLink; private final RequestOptionsFactory requestOptionsFactory; private volatile String lockETag; public DocumentServiceLeaseStore( ChangeFeedContextClient client, String containerNamePrefix, CosmosAsyncContainer leaseCollectionLink, RequestOptionsFactory requestOptionsFactory) { this.client = client; this.containerNamePrefix = containerNamePrefix; this.leaseCollectionLink = leaseCollectionLink; this.requestOptionsFactory = requestOptionsFactory; } @Override public Mono<Boolean> isInitialized() { String markerDocId = this.getStoreMarkerName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(markerDocId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); return this.client.readItem(markerDocId, new PartitionKey(markerDocId), requestOptions, InternalObjectNode.class) .flatMap(documentResourceResponse -> Mono.just(BridgeInternal.getProperties(documentResourceResponse) != null)) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (Exceptions.isNotFound(e)) { logger.info("Lease synchronization document not found"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } @Override @Override public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); InternalObjectNode containerDocument = new InternalObjectNode(); containerDocument.setId(lockId); BridgeInternal.setProperty(containerDocument, Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(), false) .map(documentResourceResponse -> { if (BridgeInternal.getProperties(documentResourceResponse) != null) { this.lockETag = BridgeInternal.getProperties(documentResourceResponse).getETag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } @Override public Mono<Boolean> releaseInitializationLock() { String lockId = this.getStoreLockName(); InternalObjectNode doc = new InternalObjectNode(); doc.setId(lockId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createItemRequestOptions( ServiceItemLeaseV1.fromDocument(doc)); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } requestOptions.setIfMatchETag(this.lockETag); return this.client.deleteItem(lockId, new PartitionKey(lockId), requestOptions) .map(documentResourceResponse -> { if (documentResourceResponse.getItem() != null) { this.lockETag = null; return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosException) { CosmosException e = (CosmosException) throwable; if (e.getStatusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); } private String getStoreMarkerName() { return this.containerNamePrefix + ".info"; } private String getStoreLockName() { return this.containerNamePrefix + ".lock"; } }
compiles with jackson 2.10
public void isValidJSON(final String json) { try { final JsonParser parser = new JsonFactory().createParser(json); while (parser.nextToken() != null) { } } catch (IOException ex) { fail("Diagnostic string is not in json format ", ex); } }
final JsonParser parser = new JsonFactory().createParser(json);
public void isValidJSON(final String json) { try { final JsonParser parser = new JsonFactory().createParser(json); while (parser.nextToken() != null) { } } catch (IOException ex) { fail("Diagnostic string is not in json format ", ex); } }
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final DateTimeFormatter RESPONSE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT; private static final String tempMachineId = getTempMachineId(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosAsyncDatabase cosmosAsyncDatabase; private CosmosContainer container; private CosmosAsyncContainer cosmosAsyncContainer; private static String getTempMachineId() { Field field = null; try { field = RxDocumentClientImpl.class.getDeclaredField("tempMachineId"); } catch (NoSuchFieldException e) { fail(e.toString()); } field.setAccessible(true); try { return (String)field.get(null); } catch (IllegalAccessException e) { fail(e.toString()); return null; } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.gatewayClient).isNull(); gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient()); cosmosAsyncDatabase = directClient.asyncClient().getDatabase(cosmosAsyncContainer.getDatabase().getId()); container = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { if (this.gatewayClient != null) { this.gatewayClient.close(); } if (this.directClient != null) { this.directClient.close(); } } @DataProvider(name = "query") private Object[][] query() { return new Object[][]{ new Object[] { "Select * from c where c.id = 'wrongId'", true }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", true }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", true }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, }; } @DataProvider(name = "readAllItemsOfLogicalPartition") private Object[][] readAllItemsOfLogicalPartition() { return new Object[][]{ new Object[] { 1, true }, new Object[] { 5, null }, new Object[] { 20, null }, new Object[] { 1, false }, new Object[] { 5, false }, new Object[] { 20, false }, }; } @DataProvider(name = "connectionStateListenerArgProvider") public Object[][] connectionStateListenerArgProvider() { return new Object[][]{ {true}, {false} }; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnostics() throws Exception { CosmosClient testGatewayClient = null; try { testGatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); Thread.sleep(2000); CosmosContainer container = testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), testGatewayClient.asyncClient()); isValidJSON(diagnostics); } finally { if (testGatewayClient != null) { testGatewayClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = this.container.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = this.container.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"statusCode\":404"); assertThat(diagnostics).contains("\"operationType\":\"Read\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"Entity with the specified id does not exist in the system."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateRegionContacted(createResponse.getDiagnostics(), this.container.asyncContainer.getDatabase().getClient()); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); isValidJSON(diagnostics); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void systemDiagnosticsForSystemStateInformation() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = this.container.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("systemInformation"); assertThat(diagnostics).contains("usedMemory"); assertThat(diagnostics).contains("availableMemory"); assertThat(diagnostics).contains("systemCpuLoad"); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnostics() throws Exception { CosmosClient testDirectClient = null; try { testDirectClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("\"gatewayStatistics\":null"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), testDirectClient.asyncClient()); isValidJSON(diagnostics); try { cosmosContainer.createItem(internalObjectNode); fail("expected 409"); } catch (CosmosException e) { diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validateTransportRequestTimelineDirect(e.getDiagnostics().toString()); } } finally { if (testDirectClient != null) { testDirectClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void requestSessionTokenDiagnostics() { CosmosClient testSessionTokenClient = null; try { testSessionTokenClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testSessionTokenClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":null"); String sessionToken = createResponse.getSessionToken(); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey(BridgeInternal.getProperties(createResponse).getId()), InternalObjectNode.class); diagnostics = readResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", sessionToken)); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey( BridgeInternal.getProperties(createResponse).getId())); internalObjectNode = getInternalObjectNode(); batch.createItemOperation(internalObjectNode); CosmosBatchResponse batchResponse = cosmosContainer.executeCosmosBatch(batch, new CosmosBatchRequestOptions().setSessionToken("0:-1 diagnostics = batchResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":\"0:-1 } finally { if (testSessionTokenClient != null) { testSessionTokenClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryPlanDiagnostics() throws JsonProcessingException { CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); queryList.add("Select * from c"); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); queryList.add("Select * from c where c.id = 'wrongId'"); for(String query : queryList) { int feedResponseCounter = 0; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = cosmosContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); if (feedResponseCounter == 0) { assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)="); String requestTimeLine = OBJECT_MAPPER.writeValueAsString(feedResponse.getCosmosDiagnostics().getFeedResponseDiagnostics().getQueryPlanDiagnosticsContext().getRequestTimeline()); assertThat(requestTimeLine).contains("connectionConfigured"); assertThat(requestTimeLine).contains("requestSent"); assertThat(requestTimeLine).contains("transitTime"); assertThat(requestTimeLine).contains("received"); } else { assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan RequestTimeline ="); } feedResponseCounter++; } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithIndexMetrics() { CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); for (String query : queryList) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); options.setIndexMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = cosmosContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); logger.info("This is query diagnostics {}", queryDiagnostics); if (feedResponse.getResponseHeaders().containsKey(HttpConstants.HttpHeaders.INDEX_UTILIZATION)) { assertThat(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION)).isNotNull(); assertThat(createFromJSONString(Utils.decodeBase64String(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION))).getUtilizedSingleIndexes()).isNotNull(); } } } } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT) public void queryMetrics(String query, Boolean qmEnabled) { CosmosContainer directContainer = this.directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } boolean qroupByFirstResponse = true; Iterator<FeedResponse<InternalObjectNode>> iterator = directContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateDirectModeQueryDiagnostics(queryDiagnostics); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryDiagnosticsOnOrderBy() { String containerId = "testcontainer"; cosmosAsyncDatabase.createContainer(containerId, "/mypk", ThroughputProperties.createManualThroughput(40000)).block(); CosmosAsyncContainer testcontainer = cosmosAsyncDatabase.getContainer(containerId); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setConsistencyLevel(ConsistencyLevel.EVENTUAL); testcontainer.createItem(getInternalObjectNode()).block(); options.setMaxDegreeOfParallelism(-1); String query = "SELECT * from c ORDER BY c._ts DESC"; CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = testcontainer.queryItems(query, options, InternalObjectNode.class); Set<String> partitionKeyRangeIds = new HashSet<>(); Set<String> pkRids = new HashSet<>(); cosmosPagedFlux.byPage().flatMap(feedResponse -> { String cosmosDiagnosticsString = feedResponse.getCosmosDiagnostics().toString(); Pattern pattern = Pattern.compile("(\"partitionKeyRangeId\":\")(\\d)"); Matcher matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); partitionKeyRangeIds.add(group); } pattern = Pattern.compile("(pkrId:)(\\d)"); matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); pkRids.add(group); } return Flux.just(feedResponse); }).blockLast(); assertThat(pkRids).isNotEmpty(); assertThat(pkRids).isEqualTo(partitionKeyRangeIds); deleteCollection(testcontainer); } private void validateDirectModeQueryDiagnostics(String diagnostics) { assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("responseStatisticsList"); assertThat(diagnostics).contains("\"gatewayStatistics\":null"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } private void validateGatewayModeQueryDiagnostics(String diagnostics) { assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"operationType\":\"Query\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"regionsContacted\""); } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT*2) public void queryDiagnosticsGatewayMode(String query, Boolean qmEnabled) { CosmosClient testDirectClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosContainer cosmosContainer = testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); List<String> itemIdList = new ArrayList<>(); for (int i = 0; i < 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); if (i % 20 == 0) { itemIdList.add(internalObjectNode.getId()); } } boolean qroupByFirstResponse = true; if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } Iterator<FeedResponse<InternalObjectNode>> iterator = cosmosContainer .queryItems(query, options, InternalObjectNode.class) .iterableByPage() .iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateGatewayModeQueryDiagnostics(queryDiagnostics); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithADifferentLocale() { Locale.setDefault(Locale.GERMAN); String query = "select * from root where root.id= \"someid\""; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); Iterator<FeedResponse<InternalObjectNode>> iterator = this.container.queryItems(query, options, InternalObjectNode.class) .iterableByPage().iterator(); double requestCharge = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); requestCharge += feedResponse.getRequestCharge(); } assertThat(requestCharge).isGreaterThan(0); Locale.setDefault(Locale.ROOT); } private static void validateQueryDiagnostics( String queryDiagnostics, Boolean qmEnabled, boolean expectQueryPlanDiagnostics) { if (qmEnabled == null || qmEnabled) { assertThat(queryDiagnostics).contains("Retrieved Document Count"); assertThat(queryDiagnostics).contains("Query Preparation Times"); assertThat(queryDiagnostics).contains("Runtime Execution Times"); assertThat(queryDiagnostics).contains("Partition Execution Timeline"); } else { assertThat(queryDiagnostics).doesNotContain("Retrieved Document Count"); assertThat(queryDiagnostics).doesNotContain("Query Preparation Times"); assertThat(queryDiagnostics).doesNotContain("Runtime Execution Times"); assertThat(queryDiagnostics).doesNotContain("Partition Execution Timeline"); } if (expectQueryPlanDiagnostics) { assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)="); } else { assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)="); } } @Test(groups = {"simple"}, dataProvider = "readAllItemsOfLogicalPartition", timeOut = TIMEOUT) public void queryMetricsForReadAllItemsOfLogicalPartition(Integer expectedItemCount, Boolean qmEnabled) { String pkValue = UUID.randomUUID().toString(); for (int i = 0; i < expectedItemCount; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode); } CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options = options.setQueryMetricsEnabled(qmEnabled); } ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5); Iterator<FeedResponse<InternalObjectNode>> iterator = this.container .readAllItems( new PartitionKey(pkValue), options, InternalObjectNode.class) .iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); int actualItemCount = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); actualItemCount += feedResponse.getResults().size(); validateQueryDiagnostics(queryDiagnostics, qmEnabled, false); } assertThat(actualItemCount).isEqualTo(expectedItemCount); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnException() throws Exception { CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); createResponse = container.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource Not Found."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\":null"); isValidJSON(diagnostics); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), client.asyncClient()); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnMetadataException() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class), Mockito.any(Duration.class))) .thenReturn(Mono.error(new CosmosException(400, "TestBadRequest"))); RxStoreModel rxGatewayStoreModel = rxGatewayStoreModel = ReflectionUtils.getGatewayProxy((RxDocumentClientImpl) client.asyncClient().getDocClientWrapper()); ReflectionUtils.setGatewayHttpClient(rxGatewayStoreModel, mockHttpClient); container.createItem(internalObjectNode); fail("request should fail as bad request"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.BADREQUEST); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"TestBadRequest\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(diagnostics).contains("\"resourceType\":\"DocumentCollection\""); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); isValidJSON(diagnostics); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void supplementalResponseStatisticsList() throws Exception { ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics(mockDiagnosticsClientContext()); for (int i = 0; i < 15; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } List<ClientSideRequestStatistics.StoreResponseStatistics> storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); ObjectMapper objectMapper = new ObjectMapper(); String diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); JsonNode jsonNode = objectMapper.readTree(diagnostics); ArrayNode supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(15); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(10); clearStoreResponseStatistics(clientSideRequestStatistics); storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); assertThat(storeResponseStatistics.size()).isEqualTo(0); for (int i = 0; i < 7; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); objectMapper = new ObjectMapper(); diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); jsonNode = objectMapper.readTree(diagnostics); supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(7); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(7); for(JsonNode node : supplementalResponseStatisticsListNode) { assertThat(node.get("storeResult").asText()).isNotNull(); String requestResponseTimeUTC = node.get("requestResponseTimeUTC").asText(); Instant instant = Instant.from(RESPONSE_TIME_FORMATTER.parse(requestResponseTimeUTC)); assertThat(Instant.now().toEpochMilli() - instant.toEpochMilli()).isLessThan(5000); assertThat(node.get("requestResponseTimeUTC")).isNotNull(); assertThat(node.get("requestOperationType")).isNotNull(); assertThat(node.get("requestSessionToken")).isNotNull(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void serializationOnVariousScenarios() { CosmosDatabaseResponse cosmosDatabase = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).read(); String diagnostics = cosmosDatabase.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"DATABASE_DESERIALIZATION\""); CosmosContainerResponse containerResponse = this.container.read(); diagnostics = containerResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"CONTAINER_DESERIALIZATION\""); TestItem testItem = new TestItem(); testItem.id = "TestId"; testItem.mypk = "TestPk"; CosmosItemResponse<TestItem> itemResponse = this.container.createItem(testItem); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); testItem.id = "TestId2"; testItem.mypk = "TestPk"; itemResponse = this.container.createItem(testItem, new PartitionKey("TestPk"), null); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).doesNotContain("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).doesNotContain("\"serializationType\":\"ITEM_DESERIALIZATION\""); TestItem readTestItem = itemResponse.getItem(); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); CosmosItemResponse<InternalObjectNode> readItemResponse = this.container.readItem(testItem.id, new PartitionKey(testItem.mypk), null, InternalObjectNode.class); InternalObjectNode properties = readItemResponse.getItem(); diagnostics = readItemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void rntbdRequestResponseLengthStatistics() throws Exception { TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); CosmosItemResponse<TestItem> createItemResponse = container.createItem(testItem); validate(createItemResponse.getDiagnostics(), testItemLength, ModelBridgeInternal.getPayloadLength(createItemResponse)); try { container.createItem(testItem); fail("expected to fail due to 409"); } catch (CosmosException e) { logger.info("Diagnostics are : {}", e.getDiagnostics()); String diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validate(e.getDiagnostics(), testItemLength, 0); } CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } @Test(groups = {"simple"}, dataProvider = "connectionStateListenerArgProvider", timeOut = TIMEOUT) public void rntbdStatistics(boolean connectionStateListenerEnabled) throws Exception { Instant beforeClientInitialization = Instant.now(); CosmosClient client1 = null; try { DirectConnectionConfig connectionConfig = DirectConnectionConfig.getDefaultConfig(); connectionConfig.setConnectionEndpointRediscoveryEnabled(connectionStateListenerEnabled); client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(connectionConfig) .buildClient(); TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = client1.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); Thread.sleep(1000); Instant beforeInitializingRntbdServiceEndpoint = Instant.now(); CosmosItemResponse<TestItem> operation1Response = container.upsertItem(testItem); Instant afterInitializingRntbdServiceEndpoint = Instant.now(); Thread.sleep(1000); Instant beforeOperation2 = Instant.now(); CosmosItemResponse<TestItem> operation2Response = container.upsertItem(testItem); Instant afterOperation2 = Instant.now(); Thread.sleep(1000); Instant beforeOperation3 = Instant.now(); CosmosItemResponse<TestItem> operation3Response = container.upsertItem(testItem); Instant afterOperation3 = Instant.now(); validateRntbdStatistics(operation3Response.getDiagnostics(), beforeClientInitialization, beforeInitializingRntbdServiceEndpoint, afterInitializingRntbdServiceEndpoint, beforeOperation2, afterOperation2, beforeOperation3, afterOperation3, connectionStateListenerEnabled); CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } finally { LifeCycleUtils.closeQuietly(client1); } } private void validateRntbdStatistics(CosmosDiagnostics cosmosDiagnostics, Instant clientInitializationTime, Instant beforeInitializingRntbdServiceEndpoint, Instant afterInitializingRntbdServiceEndpoint, Instant beforeOperation2, Instant afterOperation2, Instant beforeOperation3, Instant afterOperation3, boolean connectionStateListenerEnabled) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); assertThat(storeResult.get("channelTaskQueueSize").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(storeResult.get("pendingRequestsCount").asInt(-1)).isGreaterThanOrEqualTo(0); JsonNode serviceEndpointStatistics = storeResult.get("serviceEndpointStatistics"); assertThat(serviceEndpointStatistics).isNotNull(); assertThat(serviceEndpointStatistics.get("availableChannels").asInt(-1)).isGreaterThan(0); assertThat(serviceEndpointStatistics.get("acquiredChannels").asInt(-1)).isEqualTo(0); assertThat(serviceEndpointStatistics.get("inflightRequests").asInt(-1)).isEqualTo(1); assertThat(serviceEndpointStatistics.get("isClosed").asBoolean()).isEqualTo(false); JsonNode connectionStateListenerMetrics = serviceEndpointStatistics.get("cerMetrics"); if (connectionStateListenerEnabled) { assertThat(connectionStateListenerMetrics).isNotNull(); assertThat(connectionStateListenerMetrics.get("lastCallTimestamp")).isNull(); assertThat(connectionStateListenerMetrics.get("lastActionableContext")).isNull(); } else { assertThat(connectionStateListenerMetrics).isNull(); } Instant beforeInitializationThreshold = beforeInitializingRntbdServiceEndpoint.minusMillis(1); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isAfterOrEqualTo(beforeInitializationThreshold); Instant afterInitializationThreshold = afterInitializingRntbdServiceEndpoint.plusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isBeforeOrEqualTo(afterInitializationThreshold); Instant afterOperation2Threshold = afterOperation2.plusMillis(2); Instant beforeOperation2Threshold = beforeOperation2.minusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("lastRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); assertThat(Instant.parse(serviceEndpointStatistics.get("lastSuccessfulRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); } private void validate(CosmosDiagnostics cosmosDiagnostics, int expectedRequestPayloadSize, int expectedResponsePayloadSize) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); boolean hasPayload = storeResult.get("exceptionMessage") == null; assertThat(storeResult).isNotNull(); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("requestPayloadLengthInBytes").asInt(-1)).isEqualTo(expectedRequestPayloadSize); if (hasPayload) { assertThat(storeResult.get("responsePayloadLengthInBytes").asInt(-1)).isEqualTo(expectedResponsePayloadSize); } assertThat(storeResult.get("rntbdResponseLengthInBytes").asInt(-1)).isGreaterThan(expectedResponsePayloadSize); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void addressResolutionStatistics() { CosmosClient client1 = null; CosmosClient client2 = null; String databaseId = DatabaseForTest.generateId(); String containerId = UUID.randomUUID().toString(); CosmosDatabase cosmosDatabase = null; CosmosContainer cosmosContainer = null; try { client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); client1.createDatabase(databaseId); cosmosDatabase = client1.getDatabase(databaseId); cosmosDatabase.createContainer(containerId, "/mypk"); InternalObjectNode internalObjectNode = getInternalObjectNode(); cosmosContainer = cosmosDatabase.getContainer(containerId); CosmosItemResponse<InternalObjectNode> writeResourceResponse = cosmosContainer.createItem(internalObjectNode); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":null"); client2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosDatabase = client2.getDatabase(databaseId); cosmosContainer = cosmosDatabase.getContainer(containerId); AsyncDocumentClient asyncDocumentClient = client2.asyncClient().getContextClient(); GlobalAddressResolver addressResolver = (GlobalAddressResolver) FieldUtils.readField(asyncDocumentClient, "addressResolver", true); @SuppressWarnings("rawtypes") Map addressCacheByEndpoint = (Map) FieldUtils.readField(addressResolver, "addressCacheByEndpoint", true); Object endpointCache = addressCacheByEndpoint.values().toArray()[0]; GatewayAddressCache addressCache = (GatewayAddressCache) FieldUtils.readField(endpointCache, "addressCache", true); HttpClient httpClient = httpClient(true); FieldUtils.writeField(addressCache, "httpClient", httpClient, true); new Thread(() -> { try { Thread.sleep(5000); HttpClient httpClient1 = httpClient(false); FieldUtils.writeField(addressCache, "httpClient", httpClient1, true); } catch (Exception e) { fail(e.getMessage()); } }).start(); PartitionKey partitionKey = new PartitionKey(internalObjectNode.get("mypk")); CosmosItemResponse<InternalObjectNode> readResourceResponse = cosmosContainer.readItem(internalObjectNode.getId(), partitionKey, new CosmosItemRequestOptions(), InternalObjectNode.class); assertThat(readResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(readResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":\"io.netty" + ".channel.AbstractChannel$AnnotatedConnectException: Connection refused"); } catch (Exception ex) { logger.error("Error in test addressResolutionStatistics", ex); fail("This test should not throw exception " + ex); } finally { safeDeleteSyncDatabase(cosmosDatabase); if (client1 != null) { client1.close(); } if (client2 != null) { client2.close(); } } } private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", uuid); return internalObjectNode; } private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", pkValue); return internalObjectNode; } private List<ClientSideRequestStatistics.StoreResponseStatistics> getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); @SuppressWarnings({"unchecked"}) List<ClientSideRequestStatistics.StoreResponseStatistics> list = (List<ClientSideRequestStatistics.StoreResponseStatistics>) storeResponseStatisticsField.get(requestStatistics); return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); storeResponseStatisticsField.set(requestStatistics, new ArrayList<ClientSideRequestStatistics.StoreResponseStatistics>()); } private void validateTransportRequestTimelineGateway(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"connectionConfigured\""); assertThat(diagnostics).contains("\"eventName\":\"requestSent\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"received\""); } private void validateTransportRequestTimelineDirect(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"created\""); assertThat(diagnostics).contains("\"eventName\":\"queued\""); assertThat(diagnostics).contains("\"eventName\":\"channelAcquisitionStarted\""); assertThat(diagnostics).contains("\"eventName\":\"pipelined\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"decodeTime"); assertThat(diagnostics).contains("\"eventName\":\"received\""); assertThat(diagnostics).contains("\"eventName\":\"completed\""); assertThat(diagnostics).contains("\"startTimeUTC\""); assertThat(diagnostics).contains("\"durationInMilliSecs\""); } private HttpClient httpClient(boolean fakeProxy) { HttpClientConfig httpClientConfig; if(fakeProxy) { httpClientConfig = new HttpClientConfig(new Configs()) .withProxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))); } else { httpClientConfig = new HttpClientConfig(new Configs()); } return HttpClient.createFixed(httpClientConfig); } private IndexUtilizationInfo createFromJSONString(String jsonString) { ObjectMapper indexUtilizationInfoObjectMapper = new ObjectMapper(); IndexUtilizationInfo indexUtilizationInfo = null; try { indexUtilizationInfo = indexUtilizationInfoObjectMapper.readValue(jsonString, IndexUtilizationInfo.class); } catch (JsonProcessingException e) { logger.error("Json not correctly formed ", e); } return indexUtilizationInfo; } private void validateRegionContacted(CosmosDiagnostics cosmosDiagnostics, CosmosAsyncClient cosmosAsyncClient) throws Exception { RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(cosmosAsyncClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(rxDocumentClient); LocationCache locationCache = ReflectionUtils.getLocationCache(globalEndpointManager); Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); Class<?> DatabaseAccountLocationsInfoClass = Class.forName("com.azure.cosmos.implementation.routing" + ".LocationCache$DatabaseAccountLocationsInfo"); Field availableWriteEndpointByLocation = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteEndpointByLocation"); availableWriteEndpointByLocation.setAccessible(true); @SuppressWarnings("unchecked") Map<String, URI> map = (Map<String, URI>) availableWriteEndpointByLocation.get(locationInfo); String regionName = map.keySet().iterator().next(); assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().iterator().next()).isEqualTo(regionName.toLowerCase()); } public static class TestItem { public String id; public String mypk; public TestItem() { } } }
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final DateTimeFormatter RESPONSE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT; private static final String tempMachineId = getTempMachineId(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosAsyncDatabase cosmosAsyncDatabase; private CosmosContainer container; private CosmosAsyncContainer cosmosAsyncContainer; private static String getTempMachineId() { Field field = null; try { field = RxDocumentClientImpl.class.getDeclaredField("tempMachineId"); } catch (NoSuchFieldException e) { fail(e.toString()); } field.setAccessible(true); try { return (String)field.get(null); } catch (IllegalAccessException e) { fail(e.toString()); return null; } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.gatewayClient).isNull(); gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient()); cosmosAsyncDatabase = directClient.asyncClient().getDatabase(cosmosAsyncContainer.getDatabase().getId()); container = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { if (this.gatewayClient != null) { this.gatewayClient.close(); } if (this.directClient != null) { this.directClient.close(); } } @DataProvider(name = "query") private Object[][] query() { return new Object[][]{ new Object[] { "Select * from c where c.id = 'wrongId'", true }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", true }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", true }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", true }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId'", false }, new Object[] { "Select top 1 * from c where c.id = 'wrongId'", false }, new Object[] { "Select * from c where c.id = 'wrongId' order by c.id", false }, new Object[] { "Select count(1) from c where c.id = 'wrongId' group by c.pk", false }, new Object[] { "Select distinct c.pk from c where c.id = 'wrongId'", false }, }; } @DataProvider(name = "readAllItemsOfLogicalPartition") private Object[][] readAllItemsOfLogicalPartition() { return new Object[][]{ new Object[] { 1, true }, new Object[] { 5, null }, new Object[] { 20, null }, new Object[] { 1, false }, new Object[] { 5, false }, new Object[] { 20, false }, }; } @DataProvider(name = "connectionStateListenerArgProvider") public Object[][] connectionStateListenerArgProvider() { return new Object[][]{ {true}, {false} }; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnostics() throws Exception { CosmosClient testGatewayClient = null; try { testGatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); Thread.sleep(2000); CosmosContainer container = testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), testGatewayClient.asyncClient()); isValidJSON(diagnostics); } finally { if (testGatewayClient != null) { testGatewayClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void gatewayDiagnosticsOnException() throws Exception { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; try { createResponse = this.container.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = this.container.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"statusCode\":404"); assertThat(diagnostics).contains("\"operationType\":\"Read\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"Entity with the specified id does not exist in the system."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotNull(); validateRegionContacted(createResponse.getDiagnostics(), this.container.asyncContainer.getDatabase().getClient()); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); isValidJSON(diagnostics); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void systemDiagnosticsForSystemStateInformation() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = this.container.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("systemInformation"); assertThat(diagnostics).contains("usedMemory"); assertThat(diagnostics).contains("availableMemory"); assertThat(diagnostics).contains("systemCpuLoad"); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnostics() throws Exception { CosmosClient testDirectClient = null; try { testDirectClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("\"gatewayStatistics\":null"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsAnyOf( "\"machineId\":\"" + tempMachineId + "\"", "\"machineId\":\"" + ClientTelemetry.getMachineId(null) + "\"" ); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(createResponse.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), testDirectClient.asyncClient()); isValidJSON(diagnostics); try { cosmosContainer.createItem(internalObjectNode); fail("expected 409"); } catch (CosmosException e) { diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validateTransportRequestTimelineDirect(e.getDiagnostics().toString()); } } finally { if (testDirectClient != null) { testDirectClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void requestSessionTokenDiagnostics() { CosmosClient testSessionTokenClient = null; try { testSessionTokenClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testSessionTokenClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":null"); String sessionToken = createResponse.getSessionToken(); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey(BridgeInternal.getProperties(createResponse).getId()), InternalObjectNode.class); diagnostics = readResponse.getDiagnostics().toString(); assertThat(diagnostics).contains(String.format("\"requestSessionToken\":\"%s\"", sessionToken)); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey( BridgeInternal.getProperties(createResponse).getId())); internalObjectNode = getInternalObjectNode(); batch.createItemOperation(internalObjectNode); CosmosBatchResponse batchResponse = cosmosContainer.executeCosmosBatch(batch, new CosmosBatchRequestOptions().setSessionToken("0:-1 diagnostics = batchResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"requestSessionToken\":\"0:-1 } finally { if (testSessionTokenClient != null) { testSessionTokenClient.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryPlanDiagnostics() throws JsonProcessingException { CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); queryList.add("Select * from c"); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); queryList.add("Select * from c where c.id = 'wrongId'"); for(String query : queryList) { int feedResponseCounter = 0; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = cosmosContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); if (feedResponseCounter == 0) { assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)="); String requestTimeLine = OBJECT_MAPPER.writeValueAsString(feedResponse.getCosmosDiagnostics().getFeedResponseDiagnostics().getQueryPlanDiagnosticsContext().getRequestTimeline()); assertThat(requestTimeLine).contains("connectionConfigured"); assertThat(requestTimeLine).contains("requestSent"); assertThat(requestTimeLine).contains("transitTime"); assertThat(requestTimeLine).contains("received"); } else { assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan RequestTimeline ="); } feedResponseCounter++; } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithIndexMetrics() { CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); List<String> itemIdList = new ArrayList<>(); for(int i = 0; i< 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); if(i%20 == 0) { itemIdList.add(internalObjectNode.getId()); } } String queryDiagnostics = null; List<String> queryList = new ArrayList<>(); StringBuilder queryBuilder = new StringBuilder("SELECT * from c where c.mypk in ("); for(int i = 0 ; i < itemIdList.size(); i++){ queryBuilder.append("'").append(itemIdList.get(i)).append("'"); if(i < (itemIdList.size()-1)) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } queryList.add(queryBuilder.toString()); for (String query : queryList) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setQueryMetricsEnabled(true); options.setIndexMetricsEnabled(true); Iterator<FeedResponse<InternalObjectNode>> iterator = cosmosContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); logger.info("This is query diagnostics {}", queryDiagnostics); if (feedResponse.getResponseHeaders().containsKey(HttpConstants.HttpHeaders.INDEX_UTILIZATION)) { assertThat(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION)).isNotNull(); assertThat(createFromJSONString(Utils.decodeBase64String(feedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.INDEX_UTILIZATION))).getUtilizedSingleIndexes()).isNotNull(); } } } } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT) public void queryMetrics(String query, Boolean qmEnabled) { CosmosContainer directContainer = this.directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } boolean qroupByFirstResponse = true; Iterator<FeedResponse<InternalObjectNode>> iterator = directContainer.queryItems(query, options, InternalObjectNode.class).iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateDirectModeQueryDiagnostics(queryDiagnostics); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryDiagnosticsOnOrderBy() { String containerId = "testcontainer"; cosmosAsyncDatabase.createContainer(containerId, "/mypk", ThroughputProperties.createManualThroughput(40000)).block(); CosmosAsyncContainer testcontainer = cosmosAsyncDatabase.getContainer(containerId); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setConsistencyLevel(ConsistencyLevel.EVENTUAL); testcontainer.createItem(getInternalObjectNode()).block(); options.setMaxDegreeOfParallelism(-1); String query = "SELECT * from c ORDER BY c._ts DESC"; CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = testcontainer.queryItems(query, options, InternalObjectNode.class); Set<String> partitionKeyRangeIds = new HashSet<>(); Set<String> pkRids = new HashSet<>(); cosmosPagedFlux.byPage().flatMap(feedResponse -> { String cosmosDiagnosticsString = feedResponse.getCosmosDiagnostics().toString(); Pattern pattern = Pattern.compile("(\"partitionKeyRangeId\":\")(\\d)"); Matcher matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); partitionKeyRangeIds.add(group); } pattern = Pattern.compile("(pkrId:)(\\d)"); matcher = pattern.matcher(cosmosDiagnosticsString); while (matcher.find()) { String group = matcher.group(2); pkRids.add(group); } return Flux.just(feedResponse); }).blockLast(); assertThat(pkRids).isNotEmpty(); assertThat(pkRids).isEqualTo(partitionKeyRangeIds); deleteCollection(testcontainer); } private void validateDirectModeQueryDiagnostics(String diagnostics) { assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("responseStatisticsList"); assertThat(diagnostics).contains("\"gatewayStatistics\":null"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } private void validateGatewayModeQueryDiagnostics(String diagnostics) { assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"operationType\":\"Query\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"regionsContacted\""); } @Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT*2) public void queryDiagnosticsGatewayMode(String query, Boolean qmEnabled) { CosmosClient testDirectClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosContainer cosmosContainer = testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); List<String> itemIdList = new ArrayList<>(); for (int i = 0; i < 100; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); if (i % 20 == 0) { itemIdList.add(internalObjectNode.getId()); } } boolean qroupByFirstResponse = true; if (qmEnabled != null) { options.setQueryMetricsEnabled(qmEnabled); } Iterator<FeedResponse<InternalObjectNode>> iterator = cosmosContainer .queryItems(query, options, InternalObjectNode.class) .iterableByPage() .iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); assertThat(feedResponse.getResults().size()).isEqualTo(0); if (!query.contains("group by") || qroupByFirstResponse) { validateQueryDiagnostics(queryDiagnostics, qmEnabled, true); validateGatewayModeQueryDiagnostics(queryDiagnostics); if (query.contains("group by")) { qroupByFirstResponse = false; } } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryMetricsWithADifferentLocale() { Locale.setDefault(Locale.GERMAN); String query = "select * from root where root.id= \"someid\""; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); Iterator<FeedResponse<InternalObjectNode>> iterator = this.container.queryItems(query, options, InternalObjectNode.class) .iterableByPage().iterator(); double requestCharge = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); requestCharge += feedResponse.getRequestCharge(); } assertThat(requestCharge).isGreaterThan(0); Locale.setDefault(Locale.ROOT); } private static void validateQueryDiagnostics( String queryDiagnostics, Boolean qmEnabled, boolean expectQueryPlanDiagnostics) { if (qmEnabled == null || qmEnabled) { assertThat(queryDiagnostics).contains("Retrieved Document Count"); assertThat(queryDiagnostics).contains("Query Preparation Times"); assertThat(queryDiagnostics).contains("Runtime Execution Times"); assertThat(queryDiagnostics).contains("Partition Execution Timeline"); } else { assertThat(queryDiagnostics).doesNotContain("Retrieved Document Count"); assertThat(queryDiagnostics).doesNotContain("Query Preparation Times"); assertThat(queryDiagnostics).doesNotContain("Runtime Execution Times"); assertThat(queryDiagnostics).doesNotContain("Partition Execution Timeline"); } if (expectQueryPlanDiagnostics) { assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)="); } else { assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)="); assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)="); } } @Test(groups = {"simple"}, dataProvider = "readAllItemsOfLogicalPartition", timeOut = TIMEOUT) public void queryMetricsForReadAllItemsOfLogicalPartition(Integer expectedItemCount, Boolean qmEnabled) { String pkValue = UUID.randomUUID().toString(); for (int i = 0; i < expectedItemCount; i++) { InternalObjectNode internalObjectNode = getInternalObjectNode(pkValue); CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode); } CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (qmEnabled != null) { options = options.setQueryMetricsEnabled(qmEnabled); } ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5); Iterator<FeedResponse<InternalObjectNode>> iterator = this.container .readAllItems( new PartitionKey(pkValue), options, InternalObjectNode.class) .iterableByPage().iterator(); assertThat(iterator.hasNext()).isTrue(); int actualItemCount = 0; while (iterator.hasNext()) { FeedResponse<InternalObjectNode> feedResponse = iterator.next(); String queryDiagnostics = feedResponse.getCosmosDiagnostics().toString(); actualItemCount += feedResponse.getResults().size(); validateQueryDiagnostics(queryDiagnostics, qmEnabled, false); } assertThat(actualItemCount).isEqualTo(expectedItemCount); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnException() throws Exception { CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = null; CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); createResponse = container.createItem(internalObjectNode); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey")); CosmosItemResponse<InternalObjectNode> readResponse = cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(), new PartitionKey("wrongPartitionKey"), InternalObjectNode.class); fail("request should fail as partition key is wrong"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); assertThat(diagnostics).contains("\"backendLatencyInMs\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource Not Found."); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\":null"); isValidJSON(diagnostics); validateTransportRequestTimelineDirect(diagnostics); validateRegionContacted(createResponse.getDiagnostics(), client.asyncClient()); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void directDiagnosticsOnMetadataException() { InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosClient client = null; try { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer container = client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class), Mockito.any(Duration.class))) .thenReturn(Mono.error(new CosmosException(400, "TestBadRequest"))); RxStoreModel rxGatewayStoreModel = rxGatewayStoreModel = ReflectionUtils.getGatewayProxy((RxDocumentClientImpl) client.asyncClient().getDocClientWrapper()); ReflectionUtils.setGatewayHttpClient(rxGatewayStoreModel, mockHttpClient); container.createItem(internalObjectNode); fail("request should fail as bad request"); } catch (CosmosException exception) { isValidJSON(exception.toString()); isValidJSON(exception.getMessage()); String diagnostics = exception.getDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.BADREQUEST); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("\"exceptionMessage\":\"TestBadRequest\""); assertThat(diagnostics).doesNotContain(("\"resourceAddress\":null")); assertThat(diagnostics).contains("\"resourceType\":\"DocumentCollection\""); assertThat(exception.getDiagnostics().getContactedRegionNames()).isNotEmpty(); assertThat(exception.getDiagnostics().getDuration()).isNotNull(); isValidJSON(diagnostics); } finally { if (client != null) { client.close(); } } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void supplementalResponseStatisticsList() throws Exception { ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics(mockDiagnosticsClientContext()); for (int i = 0; i < 15; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } List<ClientSideRequestStatistics.StoreResponseStatistics> storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); ObjectMapper objectMapper = new ObjectMapper(); String diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); JsonNode jsonNode = objectMapper.readTree(diagnostics); ArrayNode supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(15); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(10); clearStoreResponseStatistics(clientSideRequestStatistics); storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); assertThat(storeResponseStatistics.size()).isEqualTo(0); for (int i = 0; i < 7; i++) { RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Head, ResourceType.Document); clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, null, null); } storeResponseStatistics = getStoreResponseStatistics(clientSideRequestStatistics); objectMapper = new ObjectMapper(); diagnostics = objectMapper.writeValueAsString(clientSideRequestStatistics); jsonNode = objectMapper.readTree(diagnostics); supplementalResponseStatisticsListNode = (ArrayNode) jsonNode.get("supplementalResponseStatisticsList"); assertThat(storeResponseStatistics.size()).isEqualTo(7); assertThat(supplementalResponseStatisticsListNode.size()).isEqualTo(7); for(JsonNode node : supplementalResponseStatisticsListNode) { assertThat(node.get("storeResult").asText()).isNotNull(); String requestResponseTimeUTC = node.get("requestResponseTimeUTC").asText(); Instant instant = Instant.from(RESPONSE_TIME_FORMATTER.parse(requestResponseTimeUTC)); assertThat(Instant.now().toEpochMilli() - instant.toEpochMilli()).isLessThan(5000); assertThat(node.get("requestResponseTimeUTC")).isNotNull(); assertThat(node.get("requestOperationType")).isNotNull(); assertThat(node.get("requestSessionToken")).isNotNull(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void serializationOnVariousScenarios() { CosmosDatabaseResponse cosmosDatabase = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).read(); String diagnostics = cosmosDatabase.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"DATABASE_DESERIALIZATION\""); CosmosContainerResponse containerResponse = this.container.read(); diagnostics = containerResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"CONTAINER_DESERIALIZATION\""); TestItem testItem = new TestItem(); testItem.id = "TestId"; testItem.mypk = "TestPk"; CosmosItemResponse<TestItem> itemResponse = this.container.createItem(testItem); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); testItem.id = "TestId2"; testItem.mypk = "TestPk"; itemResponse = this.container.createItem(testItem, new PartitionKey("TestPk"), null); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).doesNotContain("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).doesNotContain("\"serializationType\":\"ITEM_DESERIALIZATION\""); TestItem readTestItem = itemResponse.getItem(); diagnostics = itemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); CosmosItemResponse<InternalObjectNode> readItemResponse = this.container.readItem(testItem.id, new PartitionKey(testItem.mypk), null, InternalObjectNode.class); InternalObjectNode properties = readItemResponse.getItem(); diagnostics = readItemResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"serializationType\":\"ITEM_DESERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(diagnostics).containsPattern("(?s).*?\"activityId\":\"[^\\s\"]+\".*"); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void rntbdRequestResponseLengthStatistics() throws Exception { TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = directClient.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); CosmosItemResponse<TestItem> createItemResponse = container.createItem(testItem); validate(createItemResponse.getDiagnostics(), testItemLength, ModelBridgeInternal.getPayloadLength(createItemResponse)); try { container.createItem(testItem); fail("expected to fail due to 409"); } catch (CosmosException e) { logger.info("Diagnostics are : {}", e.getDiagnostics()); String diagnostics = e.getDiagnostics().toString(); assertThat(diagnostics).contains("\"exceptionMessage\":\"[\\\"Resource with specified id or name already exists.\\\"]\""); assertThat(diagnostics).contains("\"exceptionResponseHeaders\""); assertThat(diagnostics).doesNotContain("\"exceptionResponseHeaders\": \"{}\""); validate(e.getDiagnostics(), testItemLength, 0); } CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } @Test(groups = {"simple"}, dataProvider = "connectionStateListenerArgProvider", timeOut = TIMEOUT) public void rntbdStatistics(boolean connectionStateListenerEnabled) throws Exception { Instant beforeClientInitialization = Instant.now(); CosmosClient client1 = null; try { DirectConnectionConfig connectionConfig = DirectConnectionConfig.getDefaultConfig(); connectionConfig.setConnectionEndpointRediscoveryEnabled(connectionStateListenerEnabled); client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(connectionConfig) .buildClient(); TestItem testItem = new TestItem(); testItem.id = UUID.randomUUID().toString(); testItem.mypk = UUID.randomUUID().toString(); int testItemLength = OBJECT_MAPPER.writeValueAsBytes(testItem).length; CosmosContainer container = client1.getDatabase(this.cosmosAsyncContainer.getDatabase().getId()).getContainer(this.cosmosAsyncContainer.getId()); Thread.sleep(1000); Instant beforeInitializingRntbdServiceEndpoint = Instant.now(); CosmosItemResponse<TestItem> operation1Response = container.upsertItem(testItem); Instant afterInitializingRntbdServiceEndpoint = Instant.now(); Thread.sleep(1000); Instant beforeOperation2 = Instant.now(); CosmosItemResponse<TestItem> operation2Response = container.upsertItem(testItem); Instant afterOperation2 = Instant.now(); Thread.sleep(1000); Instant beforeOperation3 = Instant.now(); CosmosItemResponse<TestItem> operation3Response = container.upsertItem(testItem); Instant afterOperation3 = Instant.now(); validateRntbdStatistics(operation3Response.getDiagnostics(), beforeClientInitialization, beforeInitializingRntbdServiceEndpoint, afterInitializingRntbdServiceEndpoint, beforeOperation2, afterOperation2, beforeOperation3, afterOperation3, connectionStateListenerEnabled); CosmosItemResponse<TestItem> readItemResponse = container.readItem(testItem.id, new PartitionKey(testItem.mypk), TestItem.class); validate(readItemResponse.getDiagnostics(), 0, ModelBridgeInternal.getPayloadLength(readItemResponse)); CosmosItemResponse<Object> deleteItemResponse = container.deleteItem(testItem, null); validate(deleteItemResponse.getDiagnostics(), 0, 0); } finally { LifeCycleUtils.closeQuietly(client1); } } private void validateRntbdStatistics(CosmosDiagnostics cosmosDiagnostics, Instant clientInitializationTime, Instant beforeInitializingRntbdServiceEndpoint, Instant afterInitializingRntbdServiceEndpoint, Instant beforeOperation2, Instant afterOperation2, Instant beforeOperation3, Instant afterOperation3, boolean connectionStateListenerEnabled) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); assertThat(storeResult.get("channelTaskQueueSize").asInt(-1)).isGreaterThanOrEqualTo(0); assertThat(storeResult.get("pendingRequestsCount").asInt(-1)).isGreaterThanOrEqualTo(0); JsonNode serviceEndpointStatistics = storeResult.get("serviceEndpointStatistics"); assertThat(serviceEndpointStatistics).isNotNull(); assertThat(serviceEndpointStatistics.get("availableChannels").asInt(-1)).isGreaterThan(0); assertThat(serviceEndpointStatistics.get("acquiredChannels").asInt(-1)).isEqualTo(0); assertThat(serviceEndpointStatistics.get("inflightRequests").asInt(-1)).isEqualTo(1); assertThat(serviceEndpointStatistics.get("isClosed").asBoolean()).isEqualTo(false); JsonNode connectionStateListenerMetrics = serviceEndpointStatistics.get("cerMetrics"); if (connectionStateListenerEnabled) { assertThat(connectionStateListenerMetrics).isNotNull(); assertThat(connectionStateListenerMetrics.get("lastCallTimestamp")).isNull(); assertThat(connectionStateListenerMetrics.get("lastActionableContext")).isNull(); } else { assertThat(connectionStateListenerMetrics).isNull(); } Instant beforeInitializationThreshold = beforeInitializingRntbdServiceEndpoint.minusMillis(1); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isAfterOrEqualTo(beforeInitializationThreshold); Instant afterInitializationThreshold = afterInitializingRntbdServiceEndpoint.plusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("createdTime").asText())) .isBeforeOrEqualTo(afterInitializationThreshold); Instant afterOperation2Threshold = afterOperation2.plusMillis(2); Instant beforeOperation2Threshold = beforeOperation2.minusMillis(2); assertThat(Instant.parse(serviceEndpointStatistics.get("lastRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); assertThat(Instant.parse(serviceEndpointStatistics.get("lastSuccessfulRequestTime").asText())) .isAfterOrEqualTo(beforeOperation2Threshold.toString()) .isBeforeOrEqualTo(afterOperation2Threshold.toString()); } private void validate(CosmosDiagnostics cosmosDiagnostics, int expectedRequestPayloadSize, int expectedResponsePayloadSize) throws Exception { ObjectNode diagnostics = (ObjectNode) OBJECT_MAPPER.readTree(cosmosDiagnostics.toString()); JsonNode responseStatisticsList = diagnostics.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); boolean hasPayload = storeResult.get("exceptionMessage") == null; assertThat(storeResult).isNotNull(); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("rntbdRequestLengthInBytes").asInt(-1)).isGreaterThan(expectedRequestPayloadSize); assertThat(storeResult.get("requestPayloadLengthInBytes").asInt(-1)).isEqualTo(expectedRequestPayloadSize); if (hasPayload) { assertThat(storeResult.get("responsePayloadLengthInBytes").asInt(-1)).isEqualTo(expectedResponsePayloadSize); } assertThat(storeResult.get("rntbdResponseLengthInBytes").asInt(-1)).isGreaterThan(expectedResponsePayloadSize); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void addressResolutionStatistics() { CosmosClient client1 = null; CosmosClient client2 = null; String databaseId = DatabaseForTest.generateId(); String containerId = UUID.randomUUID().toString(); CosmosDatabase cosmosDatabase = null; CosmosContainer cosmosContainer = null; try { client1 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); client1.createDatabase(databaseId); cosmosDatabase = client1.getDatabase(databaseId); cosmosDatabase.createContainer(containerId, "/mypk"); InternalObjectNode internalObjectNode = getInternalObjectNode(); cosmosContainer = cosmosDatabase.getContainer(containerId); CosmosItemResponse<InternalObjectNode> writeResourceResponse = cosmosContainer.createItem(internalObjectNode); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(writeResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":null"); client2 = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); cosmosDatabase = client2.getDatabase(databaseId); cosmosContainer = cosmosDatabase.getContainer(containerId); AsyncDocumentClient asyncDocumentClient = client2.asyncClient().getContextClient(); GlobalAddressResolver addressResolver = (GlobalAddressResolver) FieldUtils.readField(asyncDocumentClient, "addressResolver", true); @SuppressWarnings("rawtypes") Map addressCacheByEndpoint = (Map) FieldUtils.readField(addressResolver, "addressCacheByEndpoint", true); Object endpointCache = addressCacheByEndpoint.values().toArray()[0]; GatewayAddressCache addressCache = (GatewayAddressCache) FieldUtils.readField(endpointCache, "addressCache", true); HttpClient httpClient = httpClient(true); FieldUtils.writeField(addressCache, "httpClient", httpClient, true); new Thread(() -> { try { Thread.sleep(5000); HttpClient httpClient1 = httpClient(false); FieldUtils.writeField(addressCache, "httpClient", httpClient1, true); } catch (Exception e) { fail(e.getMessage()); } }).start(); PartitionKey partitionKey = new PartitionKey(internalObjectNode.get("mypk")); CosmosItemResponse<InternalObjectNode> readResourceResponse = cosmosContainer.readItem(internalObjectNode.getId(), partitionKey, new CosmosItemRequestOptions(), InternalObjectNode.class); assertThat(readResourceResponse.getDiagnostics().toString()).contains("addressResolutionStatistics"); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"inflightRequest\":false"); assertThat(readResourceResponse.getDiagnostics().toString()).doesNotContain("endTime=\"null\""); assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"exceptionMessage\":\"io.netty" + ".channel.AbstractChannel$AnnotatedConnectException: Connection refused"); } catch (Exception ex) { logger.error("Error in test addressResolutionStatistics", ex); fail("This test should not throw exception " + ex); } finally { safeDeleteSyncDatabase(cosmosDatabase); if (client1 != null) { client1.close(); } if (client2 != null) { client2.close(); } } } private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", uuid); return internalObjectNode; } private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); BridgeInternal.setProperty(internalObjectNode, "mypk", pkValue); return internalObjectNode; } private List<ClientSideRequestStatistics.StoreResponseStatistics> getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); @SuppressWarnings({"unchecked"}) List<ClientSideRequestStatistics.StoreResponseStatistics> list = (List<ClientSideRequestStatistics.StoreResponseStatistics>) storeResponseStatisticsField.get(requestStatistics); return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); storeResponseStatisticsField.set(requestStatistics, new ArrayList<ClientSideRequestStatistics.StoreResponseStatistics>()); } private void validateTransportRequestTimelineGateway(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"connectionConfigured\""); assertThat(diagnostics).contains("\"eventName\":\"requestSent\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"received\""); } private void validateTransportRequestTimelineDirect(String diagnostics) { assertThat(diagnostics).contains("\"eventName\":\"created\""); assertThat(diagnostics).contains("\"eventName\":\"queued\""); assertThat(diagnostics).contains("\"eventName\":\"channelAcquisitionStarted\""); assertThat(diagnostics).contains("\"eventName\":\"pipelined\""); assertThat(diagnostics).contains("\"eventName\":\"transitTime\""); assertThat(diagnostics).contains("\"eventName\":\"decodeTime"); assertThat(diagnostics).contains("\"eventName\":\"received\""); assertThat(diagnostics).contains("\"eventName\":\"completed\""); assertThat(diagnostics).contains("\"startTimeUTC\""); assertThat(diagnostics).contains("\"durationInMilliSecs\""); } private HttpClient httpClient(boolean fakeProxy) { HttpClientConfig httpClientConfig; if(fakeProxy) { httpClientConfig = new HttpClientConfig(new Configs()) .withProxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))); } else { httpClientConfig = new HttpClientConfig(new Configs()); } return HttpClient.createFixed(httpClientConfig); } private IndexUtilizationInfo createFromJSONString(String jsonString) { ObjectMapper indexUtilizationInfoObjectMapper = new ObjectMapper(); IndexUtilizationInfo indexUtilizationInfo = null; try { indexUtilizationInfo = indexUtilizationInfoObjectMapper.readValue(jsonString, IndexUtilizationInfo.class); } catch (JsonProcessingException e) { logger.error("Json not correctly formed ", e); } return indexUtilizationInfo; } private void validateRegionContacted(CosmosDiagnostics cosmosDiagnostics, CosmosAsyncClient cosmosAsyncClient) throws Exception { RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(cosmosAsyncClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(rxDocumentClient); LocationCache locationCache = ReflectionUtils.getLocationCache(globalEndpointManager); Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); Class<?> DatabaseAccountLocationsInfoClass = Class.forName("com.azure.cosmos.implementation.routing" + ".LocationCache$DatabaseAccountLocationsInfo"); Field availableWriteEndpointByLocation = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteEndpointByLocation"); availableWriteEndpointByLocation.setAccessible(true); @SuppressWarnings("unchecked") Map<String, URI> map = (Map<String, URI>) availableWriteEndpointByLocation.get(locationInfo); String regionName = map.keySet().iterator().next(); assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().iterator().next()).isEqualTo(regionName.toLowerCase()); } public static class TestItem { public String id; public String mypk; public TestItem() { } } }
updateAndGet might be a better one here, will update in next iterator
public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; }
if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) {
public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
Do we need this setting binder type?
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof BindingServiceProperties) { BindingServiceProperties bindingServiceProperties = (BindingServiceProperties) bean; if (bindingServiceProperties.getBinders().isEmpty()) { BinderProperties kafkaBinderSourceProperty = new BinderProperties(); kafkaBinderSourceProperty.setType(KAKFA_BINDER_TYPE); configureBinderSources(kafkaBinderSourceProperty, AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); Map<String, BinderProperties> kafkaBinderPropertyMap = new HashMap<>(); kafkaBinderPropertyMap.put(KAKFA_BINDER_DEFAULT_NAME, kafkaBinderSourceProperty); bindingServiceProperties.setBinders(kafkaBinderPropertyMap); } else { for (Map.Entry<String, BinderProperties> entry : bindingServiceProperties.getBinders().entrySet()) { if (entry.getKey() != null && entry.getValue() != null && (KAKFA_BINDER_TYPE.equalsIgnoreCase(entry.getValue().getType()) || KAKFA_BINDER_DEFAULT_NAME.equalsIgnoreCase(entry.getKey()))) { configureBinderSources(entry.getValue(), buildKafkaBinderSources(entry.getValue())); } } } } return bean; }
kafkaBinderSourceProperty.setType(KAKFA_BINDER_TYPE);
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof BindingServiceProperties) { BindingServiceProperties bindingServiceProperties = (BindingServiceProperties) bean; if (bindingServiceProperties.getBinders().isEmpty()) { BinderProperties kafkaBinderSourceProperty = new BinderProperties(); configureBinderSources(kafkaBinderSourceProperty, AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); Map<String, BinderProperties> kafkaBinderPropertyMap = new HashMap<>(); kafkaBinderPropertyMap.put(KAKFA_BINDER_DEFAULT_NAME, kafkaBinderSourceProperty); bindingServiceProperties.setBinders(kafkaBinderPropertyMap); } else { for (Map.Entry<String, BinderProperties> entry : bindingServiceProperties.getBinders().entrySet()) { if (entry.getKey() != null && entry.getValue() != null && (KAKFA_BINDER_TYPE.equalsIgnoreCase(entry.getValue().getType()) || KAKFA_BINDER_DEFAULT_NAME.equalsIgnoreCase(entry.getKey()))) { configureBinderSources(entry.getValue(), buildKafkaBinderSources(entry.getValue())); } } } } return bean; }
class BindingServicePropertiesBeanPostProcessor implements BeanPostProcessor { static final String SPRING_MAIN_SOURCES_PROPERTY = "spring.main.sources"; private static final String KAKFA_BINDER_DEFAULT_NAME = "kafka"; private static final String KAKFA_BINDER_TYPE = "kafka"; @Override private String buildKafkaBinderSources(BinderProperties binderProperties) { StringBuilder sources = new StringBuilder(AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); if (binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY) != null) { sources.append("," + binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY)); } return sources.toString(); } private void configureBinderSources(BinderProperties binderProperties, String sources) { binderProperties.getEnvironment().put(SPRING_MAIN_SOURCES_PROPERTY, sources); } }
class BindingServicePropertiesBeanPostProcessor implements BeanPostProcessor { static final String SPRING_MAIN_SOURCES_PROPERTY = "spring.main.sources"; private static final String KAKFA_BINDER_DEFAULT_NAME = "kafka"; private static final String KAKFA_BINDER_TYPE = "kafka"; @Override private String buildKafkaBinderSources(BinderProperties binderProperties) { StringBuilder sources = new StringBuilder(AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); if (binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY) != null) { sources.append("," + binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY)); } return sources.toString(); } private void configureBinderSources(BinderProperties binderProperties, String sources) { binderProperties.getEnvironment().put(SPRING_MAIN_SOURCES_PROPERTY, sources); } }
Yeah, this can be ignored since we have set the binder name as "kafka"
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof BindingServiceProperties) { BindingServiceProperties bindingServiceProperties = (BindingServiceProperties) bean; if (bindingServiceProperties.getBinders().isEmpty()) { BinderProperties kafkaBinderSourceProperty = new BinderProperties(); kafkaBinderSourceProperty.setType(KAKFA_BINDER_TYPE); configureBinderSources(kafkaBinderSourceProperty, AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); Map<String, BinderProperties> kafkaBinderPropertyMap = new HashMap<>(); kafkaBinderPropertyMap.put(KAKFA_BINDER_DEFAULT_NAME, kafkaBinderSourceProperty); bindingServiceProperties.setBinders(kafkaBinderPropertyMap); } else { for (Map.Entry<String, BinderProperties> entry : bindingServiceProperties.getBinders().entrySet()) { if (entry.getKey() != null && entry.getValue() != null && (KAKFA_BINDER_TYPE.equalsIgnoreCase(entry.getValue().getType()) || KAKFA_BINDER_DEFAULT_NAME.equalsIgnoreCase(entry.getKey()))) { configureBinderSources(entry.getValue(), buildKafkaBinderSources(entry.getValue())); } } } } return bean; }
kafkaBinderSourceProperty.setType(KAKFA_BINDER_TYPE);
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof BindingServiceProperties) { BindingServiceProperties bindingServiceProperties = (BindingServiceProperties) bean; if (bindingServiceProperties.getBinders().isEmpty()) { BinderProperties kafkaBinderSourceProperty = new BinderProperties(); configureBinderSources(kafkaBinderSourceProperty, AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); Map<String, BinderProperties> kafkaBinderPropertyMap = new HashMap<>(); kafkaBinderPropertyMap.put(KAKFA_BINDER_DEFAULT_NAME, kafkaBinderSourceProperty); bindingServiceProperties.setBinders(kafkaBinderPropertyMap); } else { for (Map.Entry<String, BinderProperties> entry : bindingServiceProperties.getBinders().entrySet()) { if (entry.getKey() != null && entry.getValue() != null && (KAKFA_BINDER_TYPE.equalsIgnoreCase(entry.getValue().getType()) || KAKFA_BINDER_DEFAULT_NAME.equalsIgnoreCase(entry.getKey()))) { configureBinderSources(entry.getValue(), buildKafkaBinderSources(entry.getValue())); } } } } return bean; }
class BindingServicePropertiesBeanPostProcessor implements BeanPostProcessor { static final String SPRING_MAIN_SOURCES_PROPERTY = "spring.main.sources"; private static final String KAKFA_BINDER_DEFAULT_NAME = "kafka"; private static final String KAKFA_BINDER_TYPE = "kafka"; @Override private String buildKafkaBinderSources(BinderProperties binderProperties) { StringBuilder sources = new StringBuilder(AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); if (binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY) != null) { sources.append("," + binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY)); } return sources.toString(); } private void configureBinderSources(BinderProperties binderProperties, String sources) { binderProperties.getEnvironment().put(SPRING_MAIN_SOURCES_PROPERTY, sources); } }
class BindingServicePropertiesBeanPostProcessor implements BeanPostProcessor { static final String SPRING_MAIN_SOURCES_PROPERTY = "spring.main.sources"; private static final String KAKFA_BINDER_DEFAULT_NAME = "kafka"; private static final String KAKFA_BINDER_TYPE = "kafka"; @Override private String buildKafkaBinderSources(BinderProperties binderProperties) { StringBuilder sources = new StringBuilder(AzureKafkaSpringCloudStreamConfiguration.AZURE_KAFKA_SPRING_CLOUD_STREAM_CONFIGURATION_CLASS); if (binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY) != null) { sources.append("," + binderProperties.getEnvironment().get(SPRING_MAIN_SOURCES_PROPERTY)); } return sources.toString(); } private void configureBinderSources(BinderProperties binderProperties, String sources) { binderProperties.getEnvironment().put(SPRING_MAIN_SOURCES_PROPERTY, sources); } }
nit; String.format(..., "deleteRule")
public Mono<Void> deleteRule(String ruleName) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.deleteRule(ruleName)); }
String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules")
public Mono<Void> deleteRule(String ruleName) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "deleteRule") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.deleteRule(ruleName)); }
class ServiceBusRuleManagerAsyncClient implements AutoCloseable { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusRuleManagerAsyncClient.class); private final String entityPath; private final MessagingEntityType entityType; private final ServiceBusConnectionProcessor connectionProcessor; private final Runnable onClientClose; private final AtomicBoolean isDisposed = new AtomicBoolean(); /** * Creates a rule manager that manages rules for a Service Bus subscription. * * @param entityPath The name of the topic and subscription. * @param entityType The type of the Service Bus resource. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param onClientClose Operation to run when the client completes. */ ServiceBusRuleManagerAsyncClient(String entityPath, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, Runnable onClientClose) { this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = entityType; this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityPath; } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param options The options for the rule to add. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code options}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string, action of {@code options} is not null and not * instanceof {@link SqlRuleAction}, filter of {@code options} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, CreateRuleOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } return createRuleInternal(ruleName, options); } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param filter The filter expression against which messages will be matched. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code filter}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if ruleName is empty string, {@code filter} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, RuleFilter filter) { CreateRuleOptions options = new CreateRuleOptions(filter); return createRuleInternal(ruleName, options); } /** * Fetches all rules associated with the topic and subscription. * * @return A list of rules associated with the topic and subscription. * * @throws IllegalStateException if client is disposed. */ public Mono<List<RuleProperties>> getRules() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules") )); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::getRules); } /** * Removes the rule on the subscription identified by {@code ruleName}. * * @param ruleName Name of rule to delete. * @return A Mono that completes when the rule is deleted. * * @throws NullPointerException if {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string. * @throws ServiceBusException if cannot find filter matches {@code ruleName} in subscription. */ /** * Disposes of the {@link ServiceBusRuleManagerAsyncClient}. If the client has a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } private Mono<Void> createRuleInternal(String ruleName, CreateRuleOptions options) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "addRule") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.createRule(ruleName, options)); } }
class ServiceBusRuleManagerAsyncClient implements AutoCloseable { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusRuleManagerAsyncClient.class); private final String entityPath; private final MessagingEntityType entityType; private final ServiceBusConnectionProcessor connectionProcessor; private final Runnable onClientClose; private final AtomicBoolean isDisposed = new AtomicBoolean(); /** * Creates a rule manager that manages rules for a Service Bus subscription. * * @param entityPath The name of the topic and subscription. * @param entityType The type of the Service Bus resource. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param onClientClose Operation to run when the client completes. */ ServiceBusRuleManagerAsyncClient(String entityPath, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, Runnable onClientClose) { this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityPath; } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param options The options for the rule to add. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code options}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string, action of {@code options} is not null and not * instanceof {@link SqlRuleAction}, filter of {@code options} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, CreateRuleOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } return createRuleInternal(ruleName, options); } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param filter The filter expression against which messages will be matched. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code filter}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if ruleName is empty string, {@code filter} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, RuleFilter filter) { CreateRuleOptions options = new CreateRuleOptions(filter); return createRuleInternal(ruleName, options); } /** * Fetches all rules associated with the topic and subscription. * * @return A list of rules associated with the topic and subscription. * * @throws IllegalStateException if client is disposed. * @throws UnsupportedOperationException if client cannot support filter with descriptor in message body. */ public Flux<RuleProperties> getRules() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules") )); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(ServiceBusManagementNode::getRules); } /** * Removes the rule on the subscription identified by {@code ruleName}. * * @param ruleName Name of rule to delete. * @return A Mono that completes when the rule is deleted. * * @throws NullPointerException if {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string. * @throws ServiceBusException if cannot find filter matches {@code ruleName} in subscription. */ /** * Disposes of the {@link ServiceBusRuleManagerAsyncClient}. If the client has a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } private Mono<Void> createRuleInternal(String ruleName, CreateRuleOptions options) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "createRule") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.createRule(ruleName, options)); } }
what causes this change?
protected Mono<TopicAuthorizationRule> createChildResourceAsync() { final TopicAuthorizationRule self = this; return this.manager().serviceClient().getTopics().createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), this.innerModel()) .map(inner -> { setInner(inner); return self; }); }
this.innerModel())
protected Mono<TopicAuthorizationRule> createChildResourceAsync() { final TopicAuthorizationRule self = this; return this.manager().serviceClient().getTopics().createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), this.innerModel()) .map(inner -> { setInner(inner); return self; }); }
class TopicAuthorizationRuleImpl extends AuthorizationRuleBaseImpl<TopicAuthorizationRule, TopicImpl, SBAuthorizationRuleInner, TopicAuthorizationRuleImpl, ServiceBusManager> implements TopicAuthorizationRule, TopicAuthorizationRule.Definition, TopicAuthorizationRule.Update { private final String namespaceName; TopicAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String topicName, String name, SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, topicName); } @Override public String namespaceName() { return this.namespaceName; } @Override public String topicName() { return this.parentName; } @Override protected Mono<SBAuthorizationRuleInner> getInnerAsync() { return this.manager().serviceClient().getTopics() .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override @Override protected Mono<AccessKeysInner> getKeysInnerAsync() { return this.manager().serviceClient().getTopics() .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override protected Mono<AccessKeysInner> regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { return this.manager().serviceClient().getTopics().regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), regenerateAccessKeyParameters); } }
class TopicAuthorizationRuleImpl extends AuthorizationRuleBaseImpl<TopicAuthorizationRule, TopicImpl, SBAuthorizationRuleInner, TopicAuthorizationRuleImpl, ServiceBusManager> implements TopicAuthorizationRule, TopicAuthorizationRule.Definition, TopicAuthorizationRule.Update { private final String namespaceName; TopicAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String topicName, String name, SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, topicName); } @Override public String namespaceName() { return this.namespaceName; } @Override public String topicName() { return this.parentName; } @Override protected Mono<SBAuthorizationRuleInner> getInnerAsync() { return this.manager().serviceClient().getTopics() .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override @Override protected Mono<AccessKeysInner> getKeysInnerAsync() { return this.manager().serviceClient().getTopics() .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override protected Mono<AccessKeysInner> regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { return this.manager().serviceClient().getTopics().regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), regenerateAccessKeyParameters); } }
I believe it's m4. Paramter.isFlattened is false this time.
protected Mono<TopicAuthorizationRule> createChildResourceAsync() { final TopicAuthorizationRule self = this; return this.manager().serviceClient().getTopics().createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), this.innerModel()) .map(inner -> { setInner(inner); return self; }); }
this.innerModel())
protected Mono<TopicAuthorizationRule> createChildResourceAsync() { final TopicAuthorizationRule self = this; return this.manager().serviceClient().getTopics().createOrUpdateAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), this.innerModel()) .map(inner -> { setInner(inner); return self; }); }
class TopicAuthorizationRuleImpl extends AuthorizationRuleBaseImpl<TopicAuthorizationRule, TopicImpl, SBAuthorizationRuleInner, TopicAuthorizationRuleImpl, ServiceBusManager> implements TopicAuthorizationRule, TopicAuthorizationRule.Definition, TopicAuthorizationRule.Update { private final String namespaceName; TopicAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String topicName, String name, SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, topicName); } @Override public String namespaceName() { return this.namespaceName; } @Override public String topicName() { return this.parentName; } @Override protected Mono<SBAuthorizationRuleInner> getInnerAsync() { return this.manager().serviceClient().getTopics() .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override @Override protected Mono<AccessKeysInner> getKeysInnerAsync() { return this.manager().serviceClient().getTopics() .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override protected Mono<AccessKeysInner> regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { return this.manager().serviceClient().getTopics().regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), regenerateAccessKeyParameters); } }
class TopicAuthorizationRuleImpl extends AuthorizationRuleBaseImpl<TopicAuthorizationRule, TopicImpl, SBAuthorizationRuleInner, TopicAuthorizationRuleImpl, ServiceBusManager> implements TopicAuthorizationRule, TopicAuthorizationRule.Definition, TopicAuthorizationRule.Update { private final String namespaceName; TopicAuthorizationRuleImpl(String resourceGroupName, String namespaceName, String topicName, String name, SBAuthorizationRuleInner inner, ServiceBusManager manager) { super(name, inner, manager); this.namespaceName = namespaceName; this.withExistingParentResource(resourceGroupName, topicName); } @Override public String namespaceName() { return this.namespaceName; } @Override public String topicName() { return this.parentName; } @Override protected Mono<SBAuthorizationRuleInner> getInnerAsync() { return this.manager().serviceClient().getTopics() .getAuthorizationRuleAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override @Override protected Mono<AccessKeysInner> getKeysInnerAsync() { return this.manager().serviceClient().getTopics() .listKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name()); } @Override protected Mono<AccessKeysInner> regenerateKeysInnerAsync(RegenerateAccessKeyParameters regenerateAccessKeyParameters) { return this.manager().serviceClient().getTopics().regenerateKeysAsync(this.resourceGroupName(), this.namespaceName(), this.topicName(), this.name(), regenerateAccessKeyParameters); } }
Do we support user input options on this?
public Mono<Collection<RuleProperties>> getRules() { return isAuthorized(OPERATION_GET_RULES).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_RULES, null); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SKIP, 0); body.put(ManagementConstants.TOP, Integer.MAX_VALUE); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).map(response -> { int statusCode = MessageUtils.getMessageStatus(response.getApplicationProperties()); Collection<RuleProperties> collection; if (statusCode == ManagementConstants.OK_STATUS_CODE) { collection = getRuleProperties((AmqpValue) response.getBody()); } else if (statusCode == ManagementConstants.NO_CONTENT_STATUS_CODE) { collection = Collections.emptyList(); } else { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, "Get rules response error. Could not get rules.", getErrorContext()))); } return collection; }); }
body.put(ManagementConstants.TOP, Integer.MAX_VALUE);
return isAuthorized(OPERATION_GET_RULES).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_RULES, null); final Map<String, Object> body = new HashMap<>(2); body.put(ManagementConstants.SKIP, 0); body.put(ManagementConstants.TOP, Integer.MAX_VALUE); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createChannel; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createChannel, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createChannel = Objects.requireNonNull(createChannel, "'createChannel' cannot be null."); this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); Map<String, Object> loggingContext = new HashMap<>(1); loggingContext.put(ENTITY_PATH_KEY, entityPath); this.logger = new ClientLogger(ManagementChannel.class, loggingContext); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers, String associatedLinkName) { final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Mono.empty(); } return isAuthorized(ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE) .then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage( ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE, associatedLinkName); final Long[] longs = numbers.toArray(new Long[0]); requestMessage.setBody(new AmqpValue(Collections.singletonMap(ManagementConstants.SEQUENCE_NUMBERS, longs))); return sendWithVerify(channel, requestMessage, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getSessionState(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_GET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).flatMap(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { return monoError(logger, Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object sessionState = map.get(ManagementConstants.SESSION_STATE); if (sessionState == null) { logger.atInfo() .addKeyValue(SESSION_ID_KEY, sessionId) .log("Does not have a session state."); return Mono.empty(); } final byte[] state = ((Binary) sessionState).getArray(); return Mono.just(state); }); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName) { return peek(fromSequenceNumber, sessionId, associatedLinkName, 1) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName, int maxMessages) { return isAuthorized(OPERATION_PEEK).thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_PEEK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBody.put(ManagementConstants.MESSAGE_COUNT_KEY, maxMessages); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, message, null); }).flatMapMany(response -> { final List<ServiceBusReceivedMessage> messages = messageSerializer.deserializeList(response, ServiceBusReceivedMessage.class); return Flux.fromIterable(messages); })); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(ServiceBusReceiveMode receiveMode, String sessionId, String associatedLinkName, Iterable<Long> sequenceNumbers) { if (sequenceNumbers == null) { return fluxError(logger, new NullPointerException("'sequenceNumbers' cannot be null")); } final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Flux.empty(); } return isAuthorized(ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER) .thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage( ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER, associatedLinkName); final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.SEQUENCE_NUMBERS, numbers.toArray(new Long[0])); requestBodyMap.put(ManagementConstants.RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBodyMap.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return sendWithVerify(channel, message, null); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); return Flux.fromIterable(messageList); })); } private Throwable mapError(Throwable throwable) { if (throwable instanceof AmqpException) { return new ServiceBusException(throwable, ServiceBusErrorSource.MANAGEMENT); } return throwable; } /** * {@inheritDoc} */ @Override public Mono<OffsetDateTime> renewMessageLock(String lockToken, String associatedLinkName) { return isAuthorized(OPERATION_PEEK).then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage(ManagementConstants.OPERATION_RENEW_LOCK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, new UUID[]{UUID.fromString(lockToken)}); requestMessage.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, requestMessage, null); }).map(responseMessage -> { final List<OffsetDateTime> renewTimeList = messageSerializer.deserializeList(responseMessage, OffsetDateTime.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Service bus response empty. Could not renew message with lock token: '%s'.", lockToken), getErrorContext()))); } return renewTimeList.get(0); })); } @Override public Mono<OffsetDateTime> renewSessionLock(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_RENEW_SESSION_LOCK).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_RENEW_SESSION_LOCK, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).map(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object expirationValue = map.get(ManagementConstants.EXPIRATION); if (!(expirationValue instanceof Date)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Expiration is not of type Date when renewing session. Id: %s. Value: %s", sessionId, expirationValue), getErrorContext()))); } return ((Date) expirationValue).toInstant().atOffset(ZoneOffset.UTC); }); } /** * {@inheritDoc} */ @Override public Flux<Long> schedule(List<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, int maxLinkSize, String associatedLinkName, ServiceBusTransactionContext transactionContext) { return isAuthorized(OPERATION_SCHEDULE_MESSAGE).thenMany(createChannel.flatMap(channel -> { final Collection<Map<String, Object>> messageList = new LinkedList<>(); for (ServiceBusMessage message : messages) { message.setScheduledEnqueueTime(scheduledEnqueueTime); final Message amqpMessage = messageSerializer.serialize(message); final int payloadSize = messageSerializer.getSize(amqpMessage); final int allocationSize = Math.min(payloadSize + ManagementConstants.MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxLinkSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = amqpMessage.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format( "Error sending. Size of the payload exceeded maximum message size: %s kb", maxLinkSize / 1024); final AmqpErrorContext errorContext = channel.getErrorContext(); return monoError(logger, Exceptions.propagate(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, errorContext))); } final Map<String, Object> messageEntry = new HashMap<>(); messageEntry.put(ManagementConstants.MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(ManagementConstants.MESSAGE_ID, amqpMessage.getMessageId()); final String sessionId = amqpMessage.getGroupId(); if (!CoreUtils.isNullOrEmpty(sessionId)) { messageEntry.put(ManagementConstants.SESSION_ID, sessionId); } final String partitionKey = message.getPartitionKey(); if (!CoreUtils.isNullOrEmpty(partitionKey)) { messageEntry.put(ManagementConstants.PARTITION_KEY, partitionKey); } messageList.add(messageEntry); } final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.MESSAGES, messageList); final Message requestMessage = createManagementMessage(OPERATION_SCHEDULE_MESSAGE, associatedLinkName); requestMessage.setBody(new AmqpValue(requestBodyMap)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, requestMessage, transactionalState); }) .flatMapMany(response -> { final List<Long> sequenceNumbers = messageSerializer.deserializeList(response, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumbers)) { fluxError(logger, new AmqpException(false, String.format( "Service Bus response was empty. Could not schedule message()s."), getErrorContext())); } return Flux.fromIterable(sequenceNumbers); })); } @Override public Mono<Void> setSessionState(String sessionId, byte[] state, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_SET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_SET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); body.put(ManagementConstants.SESSION_STATE, state == null ? null : new Binary(state)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null).then(); })); } @Override public Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String sessionId, String associatedLinkName, ServiceBusTransactionContext transactionContext) { final UUID[] lockTokens = new UUID[]{UUID.fromString(lockToken)}; return isAuthorized(OPERATION_UPDATE_DISPOSITION).then(createChannel.flatMap(channel -> { logger.atVerbose() .addKeyValue("lockTokens", Arrays.toString(lockTokens)) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .addKeyValue(SESSION_ID_KEY, sessionId) .log("Update disposition of deliveries."); final Message message = createManagementMessage(OPERATION_UPDATE_DISPOSITION, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, message, transactionalState); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> createRule(String ruleName, CreateRuleOptions ruleOptions) { return isAuthorized(OPERATION_ADD_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_ADD_RULE, null); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.RULE_NAME, ruleName); body.put(ManagementConstants.RULE_DESCRIPTION, MessageUtils.encodeRuleOptionToMap(ruleName, ruleOptions)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> deleteRule(String ruleName) { return isAuthorized(OPERATION_REMOVE_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_REMOVE_RULE, null); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.RULE_NAME, ruleName); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Collection<RuleProperties>> getRules() { )).map(response -> { int statusCode = MessageUtils.getMessageStatus(response.getApplicationProperties()); Collection<RuleProperties> collection; if (statusCode == ManagementConstants.OK_STATUS_CODE) { collection = getRuleProperties((AmqpValue) response.getBody()); } else if (statusCode == ManagementConstants.NO_CONTENT_STATUS_CODE) { collection = Collections.emptyList(); } else { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, "Get rules response error. Could not get rules.", getErrorContext()))); } return collection; }); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } private Mono<Message> sendWithVerify(RequestResponseChannel channel, Message message, DeliveryState deliveryState) { return channel.sendWithAck(message, deliveryState) .handle((Message response, SynchronousSink<Message> sink) -> { if (RequestResponseUtils.isSuccessful(response)) { sink.next(response); return; } final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(response); if (statusCode == AmqpResponseCode.NO_CONTENT) { sink.next(response); return; } final String errorCondition = RequestResponseUtils.getErrorCondition(response); if (statusCode == AmqpResponseCode.NOT_FOUND) { final AmqpErrorCondition amqpErrorCondition = AmqpErrorCondition.fromString(errorCondition); if (amqpErrorCondition == AmqpErrorCondition.MESSAGE_NOT_FOUND) { logger.info("There was no matching message found."); sink.next(response); return; } else if (amqpErrorCondition == AmqpErrorCondition.SESSION_NOT_FOUND) { logger.info("There was no matching session found."); sink.next(response); return; } } final String statusDescription = RequestResponseUtils.getStatusDescription(response); final Throwable throwable = ExceptionUtil.toException(errorCondition, statusDescription, channel.getErrorContext()); logger.atWarning() .addKeyValue("status", statusCode) .addKeyValue("description", statusDescription) .addKeyValue("condition", errorCondition) .log("Operation not successful."); sink.error(throwable); }) .switchIfEmpty(Mono.error(new AmqpException(true, "No response received from management channel.", channel.getErrorContext()))) .onErrorMap(this::mapError); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults() .onErrorMap(this::mapError) .next() .handle((response, sink) -> { if (response != AmqpResponseCode.ACCEPTED && response != AmqpResponseCode.OK) { final String message = String.format("User does not have authorization to perform operation " + "[%s] on entity [%s]. Response: [%s]", operation, entityPath, response); final Throwable exc = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, message, getErrorContext()); sink.error(new ServiceBusException(exc, ServiceBusErrorSource.MANAGEMENT)); } else { sink.complete(); } }); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param associatedLinkName Name of the open receive link that first received the message. * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String associatedLinkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(ManagementConstants.MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(ManagementConstants.SERVER_TIMEOUT, serverTimeout.toMillis()); if (!CoreUtils.isNullOrEmpty(associatedLinkName)) { applicationProperties.put(ManagementConstants.ASSOCIATED_LINK_NAME_KEY, associatedLinkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * Get {@link RuleProperties} from message body. * * @param messageBody A message body which is {@link AmqpValue} type. * @return A collection of {@link RuleProperties}. * * @throws RuntimeException Get @{@link RuleProperties} from message body failed. */ @SuppressWarnings("unchecked") private Collection<RuleProperties> getRuleProperties(AmqpValue messageBody) { try { if (messageBody == null) { return Collections.emptyList(); } List<Map<String, DescribedType>> rules = ((Map<String, List<Map<String, DescribedType>>>) messageBody.getValue()) .get(ManagementConstants.RULES); if (rules == null) { return Collections.emptyList(); } Collection<RuleProperties> ruleProperties = new ArrayList<>(); for (Map<String, DescribedType> rule : rules) { DescribedType ruleDescription = rule.get(ManagementConstants.RULE_DESCRIPTION); ruleProperties.add(MessageUtils.decodeRuleDescribedType(ruleDescription)); } return ruleProperties; } catch (RuntimeException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, String.format("Get rules failed. err: %s", ex.getMessage()), getErrorContext()))); } } }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createChannel; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createChannel, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createChannel = Objects.requireNonNull(createChannel, "'createChannel' cannot be null."); this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); Map<String, Object> loggingContext = new HashMap<>(1); loggingContext.put(ENTITY_PATH_KEY, entityPath); this.logger = new ClientLogger(ManagementChannel.class, loggingContext); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers, String associatedLinkName) { final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Mono.empty(); } return isAuthorized(ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE) .then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage( ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE, associatedLinkName); final Long[] longs = numbers.toArray(new Long[0]); requestMessage.setBody(new AmqpValue(Collections.singletonMap(ManagementConstants.SEQUENCE_NUMBERS, longs))); return sendWithVerify(channel, requestMessage, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getSessionState(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_GET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).flatMap(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { return monoError(logger, Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object sessionState = map.get(ManagementConstants.SESSION_STATE); if (sessionState == null) { logger.atInfo() .addKeyValue(SESSION_ID_KEY, sessionId) .log("Does not have a session state."); return Mono.empty(); } final byte[] state = ((Binary) sessionState).getArray(); return Mono.just(state); }); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName) { return peek(fromSequenceNumber, sessionId, associatedLinkName, 1) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName, int maxMessages) { return isAuthorized(OPERATION_PEEK).thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_PEEK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBody.put(ManagementConstants.MESSAGE_COUNT_KEY, maxMessages); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, message, null); }).flatMapMany(response -> { final List<ServiceBusReceivedMessage> messages = messageSerializer.deserializeList(response, ServiceBusReceivedMessage.class); return Flux.fromIterable(messages); })); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(ServiceBusReceiveMode receiveMode, String sessionId, String associatedLinkName, Iterable<Long> sequenceNumbers) { if (sequenceNumbers == null) { return fluxError(logger, new NullPointerException("'sequenceNumbers' cannot be null")); } final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Flux.empty(); } return isAuthorized(ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER) .thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage( ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER, associatedLinkName); final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.SEQUENCE_NUMBERS, numbers.toArray(new Long[0])); requestBodyMap.put(ManagementConstants.RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBodyMap.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return sendWithVerify(channel, message, null); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); return Flux.fromIterable(messageList); })); } private Throwable mapError(Throwable throwable) { if (throwable instanceof AmqpException) { return new ServiceBusException(throwable, ServiceBusErrorSource.MANAGEMENT); } return throwable; } /** * {@inheritDoc} */ @Override public Mono<OffsetDateTime> renewMessageLock(String lockToken, String associatedLinkName) { return isAuthorized(OPERATION_PEEK).then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage(ManagementConstants.OPERATION_RENEW_LOCK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, new UUID[]{UUID.fromString(lockToken)}); requestMessage.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, requestMessage, null); }).map(responseMessage -> { final List<OffsetDateTime> renewTimeList = messageSerializer.deserializeList(responseMessage, OffsetDateTime.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Service bus response empty. Could not renew message with lock token: '%s'.", lockToken), getErrorContext()))); } return renewTimeList.get(0); })); } @Override public Mono<OffsetDateTime> renewSessionLock(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_RENEW_SESSION_LOCK).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_RENEW_SESSION_LOCK, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).map(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object expirationValue = map.get(ManagementConstants.EXPIRATION); if (!(expirationValue instanceof Date)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Expiration is not of type Date when renewing session. Id: %s. Value: %s", sessionId, expirationValue), getErrorContext()))); } return ((Date) expirationValue).toInstant().atOffset(ZoneOffset.UTC); }); } /** * {@inheritDoc} */ @Override public Flux<Long> schedule(List<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, int maxLinkSize, String associatedLinkName, ServiceBusTransactionContext transactionContext) { return isAuthorized(OPERATION_SCHEDULE_MESSAGE).thenMany(createChannel.flatMap(channel -> { final Collection<Map<String, Object>> messageList = new LinkedList<>(); for (ServiceBusMessage message : messages) { message.setScheduledEnqueueTime(scheduledEnqueueTime); final Message amqpMessage = messageSerializer.serialize(message); final int payloadSize = messageSerializer.getSize(amqpMessage); final int allocationSize = Math.min(payloadSize + ManagementConstants.MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxLinkSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = amqpMessage.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format( "Error sending. Size of the payload exceeded maximum message size: %s kb", maxLinkSize / 1024); final AmqpErrorContext errorContext = channel.getErrorContext(); return monoError(logger, Exceptions.propagate(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, errorContext))); } final Map<String, Object> messageEntry = new HashMap<>(); messageEntry.put(ManagementConstants.MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(ManagementConstants.MESSAGE_ID, amqpMessage.getMessageId()); final String sessionId = amqpMessage.getGroupId(); if (!CoreUtils.isNullOrEmpty(sessionId)) { messageEntry.put(ManagementConstants.SESSION_ID, sessionId); } final String partitionKey = message.getPartitionKey(); if (!CoreUtils.isNullOrEmpty(partitionKey)) { messageEntry.put(ManagementConstants.PARTITION_KEY, partitionKey); } messageList.add(messageEntry); } final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.MESSAGES, messageList); final Message requestMessage = createManagementMessage(OPERATION_SCHEDULE_MESSAGE, associatedLinkName); requestMessage.setBody(new AmqpValue(requestBodyMap)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, requestMessage, transactionalState); }) .flatMapMany(response -> { final List<Long> sequenceNumbers = messageSerializer.deserializeList(response, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumbers)) { fluxError(logger, new AmqpException(false, String.format( "Service Bus response was empty. Could not schedule message()s."), getErrorContext())); } return Flux.fromIterable(sequenceNumbers); })); } @Override public Mono<Void> setSessionState(String sessionId, byte[] state, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_SET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_SET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); body.put(ManagementConstants.SESSION_STATE, state == null ? null : new Binary(state)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null).then(); })); } @Override public Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String sessionId, String associatedLinkName, ServiceBusTransactionContext transactionContext) { final UUID[] lockTokens = new UUID[]{UUID.fromString(lockToken)}; return isAuthorized(OPERATION_UPDATE_DISPOSITION).then(createChannel.flatMap(channel -> { logger.atVerbose() .addKeyValue("lockTokens", Arrays.toString(lockTokens)) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .addKeyValue(SESSION_ID_KEY, sessionId) .log("Update disposition of deliveries."); final Message message = createManagementMessage(OPERATION_UPDATE_DISPOSITION, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, message, transactionalState); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> createRule(String ruleName, CreateRuleOptions ruleOptions) { return isAuthorized(OPERATION_ADD_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_ADD_RULE, null); final Map<String, Object> body = new HashMap<>(2); body.put(ManagementConstants.RULE_NAME, ruleName); body.put(ManagementConstants.RULE_DESCRIPTION, MessageUtils.encodeRuleOptionToMap(ruleName, ruleOptions)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> deleteRule(String ruleName) { return isAuthorized(OPERATION_REMOVE_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_REMOVE_RULE, null); final Map<String, Object> body = new HashMap<>(1); body.put(ManagementConstants.RULE_NAME, ruleName); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Flux<RuleProperties> getRules() { )).flatMapMany(response -> { AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(response); List<RuleProperties> list; if (statusCode == AmqpResponseCode.OK) { list = getRuleProperties((AmqpValue) response.getBody()); } else if (statusCode == AmqpResponseCode.NO_CONTENT) { list = Collections.emptyList(); } else { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, "Get rules response error. Could not get rules.", getErrorContext()))); } return Flux.fromIterable(list); }); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } private Mono<Message> sendWithVerify(RequestResponseChannel channel, Message message, DeliveryState deliveryState) { return channel.sendWithAck(message, deliveryState) .handle((Message response, SynchronousSink<Message> sink) -> { if (RequestResponseUtils.isSuccessful(response)) { sink.next(response); return; } final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(response); if (statusCode == AmqpResponseCode.NO_CONTENT) { sink.next(response); return; } final String errorCondition = RequestResponseUtils.getErrorCondition(response); if (statusCode == AmqpResponseCode.NOT_FOUND) { final AmqpErrorCondition amqpErrorCondition = AmqpErrorCondition.fromString(errorCondition); if (amqpErrorCondition == AmqpErrorCondition.MESSAGE_NOT_FOUND) { logger.info("There was no matching message found."); sink.next(response); return; } else if (amqpErrorCondition == AmqpErrorCondition.SESSION_NOT_FOUND) { logger.info("There was no matching session found."); sink.next(response); return; } } final String statusDescription = RequestResponseUtils.getStatusDescription(response); final Throwable throwable = ExceptionUtil.toException(errorCondition, statusDescription, channel.getErrorContext()); logger.atWarning() .addKeyValue("status", statusCode) .addKeyValue("description", statusDescription) .addKeyValue("condition", errorCondition) .log("Operation not successful."); sink.error(throwable); }) .switchIfEmpty(Mono.error(new AmqpException(true, "No response received from management channel.", channel.getErrorContext()))) .onErrorMap(this::mapError); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults() .onErrorMap(this::mapError) .next() .handle((response, sink) -> { if (response != AmqpResponseCode.ACCEPTED && response != AmqpResponseCode.OK) { final String message = String.format("User does not have authorization to perform operation " + "[%s] on entity [%s]. Response: [%s]", operation, entityPath, response); final Throwable exc = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, message, getErrorContext()); sink.error(new ServiceBusException(exc, ServiceBusErrorSource.MANAGEMENT)); } else { sink.complete(); } }); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param associatedLinkName Name of the open receive link that first received the message. * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String associatedLinkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(ManagementConstants.MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(ManagementConstants.SERVER_TIMEOUT, serverTimeout.toMillis()); if (!CoreUtils.isNullOrEmpty(associatedLinkName)) { applicationProperties.put(ManagementConstants.ASSOCIATED_LINK_NAME_KEY, associatedLinkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * Get {@link RuleProperties} from message body. * * @param messageBody A message body which is {@link AmqpValue} type. * @return A collection of {@link RuleProperties}. * * @throws UnsupportedOperationException if client cannot support filter with descriptor in message body. */ private List<RuleProperties> getRuleProperties(AmqpValue messageBody) { if (messageBody == null) { return Collections.emptyList(); } @SuppressWarnings("unchecked") List<Map<String, DescribedType>> rules = ((Map<String, List<Map<String, DescribedType>>>) messageBody.getValue()) .get(ManagementConstants.RULES); if (rules == null) { return Collections.emptyList(); } List<RuleProperties> ruleProperties = new ArrayList<>(); for (Map<String, DescribedType> rule : rules) { DescribedType ruleDescription = rule.get(ManagementConstants.RULE_DESCRIPTION); ruleProperties.add(MessageUtils.decodeRuleDescribedType(ruleDescription)); } return ruleProperties; } }
Same, why `ArrayList` in declaration?
public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; }
ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed();
public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; } /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; } /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
Iterator might be a better pattern in this code (than count-- and still index by hardcoded number).
public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; }
}
public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; } /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; } /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
same here is this code copied from somewhere?
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
if (countCorrelationFilter-- > 0) {
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
The .net SDK didn't support input options. Just keep same parameter with .net SDK
public Mono<Collection<RuleProperties>> getRules() { return isAuthorized(OPERATION_GET_RULES).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_RULES, null); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SKIP, 0); body.put(ManagementConstants.TOP, Integer.MAX_VALUE); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).map(response -> { int statusCode = MessageUtils.getMessageStatus(response.getApplicationProperties()); Collection<RuleProperties> collection; if (statusCode == ManagementConstants.OK_STATUS_CODE) { collection = getRuleProperties((AmqpValue) response.getBody()); } else if (statusCode == ManagementConstants.NO_CONTENT_STATUS_CODE) { collection = Collections.emptyList(); } else { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, "Get rules response error. Could not get rules.", getErrorContext()))); } return collection; }); }
body.put(ManagementConstants.TOP, Integer.MAX_VALUE);
return isAuthorized(OPERATION_GET_RULES).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_RULES, null); final Map<String, Object> body = new HashMap<>(2); body.put(ManagementConstants.SKIP, 0); body.put(ManagementConstants.TOP, Integer.MAX_VALUE); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createChannel; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createChannel, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createChannel = Objects.requireNonNull(createChannel, "'createChannel' cannot be null."); this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); Map<String, Object> loggingContext = new HashMap<>(1); loggingContext.put(ENTITY_PATH_KEY, entityPath); this.logger = new ClientLogger(ManagementChannel.class, loggingContext); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers, String associatedLinkName) { final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Mono.empty(); } return isAuthorized(ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE) .then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage( ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE, associatedLinkName); final Long[] longs = numbers.toArray(new Long[0]); requestMessage.setBody(new AmqpValue(Collections.singletonMap(ManagementConstants.SEQUENCE_NUMBERS, longs))); return sendWithVerify(channel, requestMessage, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getSessionState(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_GET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).flatMap(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { return monoError(logger, Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object sessionState = map.get(ManagementConstants.SESSION_STATE); if (sessionState == null) { logger.atInfo() .addKeyValue(SESSION_ID_KEY, sessionId) .log("Does not have a session state."); return Mono.empty(); } final byte[] state = ((Binary) sessionState).getArray(); return Mono.just(state); }); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName) { return peek(fromSequenceNumber, sessionId, associatedLinkName, 1) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName, int maxMessages) { return isAuthorized(OPERATION_PEEK).thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_PEEK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBody.put(ManagementConstants.MESSAGE_COUNT_KEY, maxMessages); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, message, null); }).flatMapMany(response -> { final List<ServiceBusReceivedMessage> messages = messageSerializer.deserializeList(response, ServiceBusReceivedMessage.class); return Flux.fromIterable(messages); })); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(ServiceBusReceiveMode receiveMode, String sessionId, String associatedLinkName, Iterable<Long> sequenceNumbers) { if (sequenceNumbers == null) { return fluxError(logger, new NullPointerException("'sequenceNumbers' cannot be null")); } final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Flux.empty(); } return isAuthorized(ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER) .thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage( ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER, associatedLinkName); final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.SEQUENCE_NUMBERS, numbers.toArray(new Long[0])); requestBodyMap.put(ManagementConstants.RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBodyMap.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return sendWithVerify(channel, message, null); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); return Flux.fromIterable(messageList); })); } private Throwable mapError(Throwable throwable) { if (throwable instanceof AmqpException) { return new ServiceBusException(throwable, ServiceBusErrorSource.MANAGEMENT); } return throwable; } /** * {@inheritDoc} */ @Override public Mono<OffsetDateTime> renewMessageLock(String lockToken, String associatedLinkName) { return isAuthorized(OPERATION_PEEK).then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage(ManagementConstants.OPERATION_RENEW_LOCK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, new UUID[]{UUID.fromString(lockToken)}); requestMessage.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, requestMessage, null); }).map(responseMessage -> { final List<OffsetDateTime> renewTimeList = messageSerializer.deserializeList(responseMessage, OffsetDateTime.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Service bus response empty. Could not renew message with lock token: '%s'.", lockToken), getErrorContext()))); } return renewTimeList.get(0); })); } @Override public Mono<OffsetDateTime> renewSessionLock(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_RENEW_SESSION_LOCK).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_RENEW_SESSION_LOCK, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).map(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object expirationValue = map.get(ManagementConstants.EXPIRATION); if (!(expirationValue instanceof Date)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Expiration is not of type Date when renewing session. Id: %s. Value: %s", sessionId, expirationValue), getErrorContext()))); } return ((Date) expirationValue).toInstant().atOffset(ZoneOffset.UTC); }); } /** * {@inheritDoc} */ @Override public Flux<Long> schedule(List<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, int maxLinkSize, String associatedLinkName, ServiceBusTransactionContext transactionContext) { return isAuthorized(OPERATION_SCHEDULE_MESSAGE).thenMany(createChannel.flatMap(channel -> { final Collection<Map<String, Object>> messageList = new LinkedList<>(); for (ServiceBusMessage message : messages) { message.setScheduledEnqueueTime(scheduledEnqueueTime); final Message amqpMessage = messageSerializer.serialize(message); final int payloadSize = messageSerializer.getSize(amqpMessage); final int allocationSize = Math.min(payloadSize + ManagementConstants.MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxLinkSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = amqpMessage.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format( "Error sending. Size of the payload exceeded maximum message size: %s kb", maxLinkSize / 1024); final AmqpErrorContext errorContext = channel.getErrorContext(); return monoError(logger, Exceptions.propagate(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, errorContext))); } final Map<String, Object> messageEntry = new HashMap<>(); messageEntry.put(ManagementConstants.MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(ManagementConstants.MESSAGE_ID, amqpMessage.getMessageId()); final String sessionId = amqpMessage.getGroupId(); if (!CoreUtils.isNullOrEmpty(sessionId)) { messageEntry.put(ManagementConstants.SESSION_ID, sessionId); } final String partitionKey = message.getPartitionKey(); if (!CoreUtils.isNullOrEmpty(partitionKey)) { messageEntry.put(ManagementConstants.PARTITION_KEY, partitionKey); } messageList.add(messageEntry); } final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.MESSAGES, messageList); final Message requestMessage = createManagementMessage(OPERATION_SCHEDULE_MESSAGE, associatedLinkName); requestMessage.setBody(new AmqpValue(requestBodyMap)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, requestMessage, transactionalState); }) .flatMapMany(response -> { final List<Long> sequenceNumbers = messageSerializer.deserializeList(response, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumbers)) { fluxError(logger, new AmqpException(false, String.format( "Service Bus response was empty. Could not schedule message()s."), getErrorContext())); } return Flux.fromIterable(sequenceNumbers); })); } @Override public Mono<Void> setSessionState(String sessionId, byte[] state, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_SET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_SET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); body.put(ManagementConstants.SESSION_STATE, state == null ? null : new Binary(state)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null).then(); })); } @Override public Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String sessionId, String associatedLinkName, ServiceBusTransactionContext transactionContext) { final UUID[] lockTokens = new UUID[]{UUID.fromString(lockToken)}; return isAuthorized(OPERATION_UPDATE_DISPOSITION).then(createChannel.flatMap(channel -> { logger.atVerbose() .addKeyValue("lockTokens", Arrays.toString(lockTokens)) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .addKeyValue(SESSION_ID_KEY, sessionId) .log("Update disposition of deliveries."); final Message message = createManagementMessage(OPERATION_UPDATE_DISPOSITION, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, message, transactionalState); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> createRule(String ruleName, CreateRuleOptions ruleOptions) { return isAuthorized(OPERATION_ADD_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_ADD_RULE, null); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.RULE_NAME, ruleName); body.put(ManagementConstants.RULE_DESCRIPTION, MessageUtils.encodeRuleOptionToMap(ruleName, ruleOptions)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> deleteRule(String ruleName) { return isAuthorized(OPERATION_REMOVE_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_REMOVE_RULE, null); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.RULE_NAME, ruleName); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Collection<RuleProperties>> getRules() { )).map(response -> { int statusCode = MessageUtils.getMessageStatus(response.getApplicationProperties()); Collection<RuleProperties> collection; if (statusCode == ManagementConstants.OK_STATUS_CODE) { collection = getRuleProperties((AmqpValue) response.getBody()); } else if (statusCode == ManagementConstants.NO_CONTENT_STATUS_CODE) { collection = Collections.emptyList(); } else { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, "Get rules response error. Could not get rules.", getErrorContext()))); } return collection; }); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } private Mono<Message> sendWithVerify(RequestResponseChannel channel, Message message, DeliveryState deliveryState) { return channel.sendWithAck(message, deliveryState) .handle((Message response, SynchronousSink<Message> sink) -> { if (RequestResponseUtils.isSuccessful(response)) { sink.next(response); return; } final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(response); if (statusCode == AmqpResponseCode.NO_CONTENT) { sink.next(response); return; } final String errorCondition = RequestResponseUtils.getErrorCondition(response); if (statusCode == AmqpResponseCode.NOT_FOUND) { final AmqpErrorCondition amqpErrorCondition = AmqpErrorCondition.fromString(errorCondition); if (amqpErrorCondition == AmqpErrorCondition.MESSAGE_NOT_FOUND) { logger.info("There was no matching message found."); sink.next(response); return; } else if (amqpErrorCondition == AmqpErrorCondition.SESSION_NOT_FOUND) { logger.info("There was no matching session found."); sink.next(response); return; } } final String statusDescription = RequestResponseUtils.getStatusDescription(response); final Throwable throwable = ExceptionUtil.toException(errorCondition, statusDescription, channel.getErrorContext()); logger.atWarning() .addKeyValue("status", statusCode) .addKeyValue("description", statusDescription) .addKeyValue("condition", errorCondition) .log("Operation not successful."); sink.error(throwable); }) .switchIfEmpty(Mono.error(new AmqpException(true, "No response received from management channel.", channel.getErrorContext()))) .onErrorMap(this::mapError); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults() .onErrorMap(this::mapError) .next() .handle((response, sink) -> { if (response != AmqpResponseCode.ACCEPTED && response != AmqpResponseCode.OK) { final String message = String.format("User does not have authorization to perform operation " + "[%s] on entity [%s]. Response: [%s]", operation, entityPath, response); final Throwable exc = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, message, getErrorContext()); sink.error(new ServiceBusException(exc, ServiceBusErrorSource.MANAGEMENT)); } else { sink.complete(); } }); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param associatedLinkName Name of the open receive link that first received the message. * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String associatedLinkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(ManagementConstants.MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(ManagementConstants.SERVER_TIMEOUT, serverTimeout.toMillis()); if (!CoreUtils.isNullOrEmpty(associatedLinkName)) { applicationProperties.put(ManagementConstants.ASSOCIATED_LINK_NAME_KEY, associatedLinkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * Get {@link RuleProperties} from message body. * * @param messageBody A message body which is {@link AmqpValue} type. * @return A collection of {@link RuleProperties}. * * @throws RuntimeException Get @{@link RuleProperties} from message body failed. */ @SuppressWarnings("unchecked") private Collection<RuleProperties> getRuleProperties(AmqpValue messageBody) { try { if (messageBody == null) { return Collections.emptyList(); } List<Map<String, DescribedType>> rules = ((Map<String, List<Map<String, DescribedType>>>) messageBody.getValue()) .get(ManagementConstants.RULES); if (rules == null) { return Collections.emptyList(); } Collection<RuleProperties> ruleProperties = new ArrayList<>(); for (Map<String, DescribedType> rule : rules) { DescribedType ruleDescription = rule.get(ManagementConstants.RULE_DESCRIPTION); ruleProperties.add(MessageUtils.decodeRuleDescribedType(ruleDescription)); } return ruleProperties; } catch (RuntimeException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, String.format("Get rules failed. err: %s", ex.getMessage()), getErrorContext()))); } } }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createChannel; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createChannel, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createChannel = Objects.requireNonNull(createChannel, "'createChannel' cannot be null."); this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); Map<String, Object> loggingContext = new HashMap<>(1); loggingContext.put(ENTITY_PATH_KEY, entityPath); this.logger = new ClientLogger(ManagementChannel.class, loggingContext); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers, String associatedLinkName) { final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Mono.empty(); } return isAuthorized(ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE) .then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage( ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE, associatedLinkName); final Long[] longs = numbers.toArray(new Long[0]); requestMessage.setBody(new AmqpValue(Collections.singletonMap(ManagementConstants.SEQUENCE_NUMBERS, longs))); return sendWithVerify(channel, requestMessage, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getSessionState(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_GET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_GET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).flatMap(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { return monoError(logger, Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object sessionState = map.get(ManagementConstants.SESSION_STATE); if (sessionState == null) { logger.atInfo() .addKeyValue(SESSION_ID_KEY, sessionId) .log("Does not have a session state."); return Mono.empty(); } final byte[] state = ((Binary) sessionState).getArray(); return Mono.just(state); }); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName) { return peek(fromSequenceNumber, sessionId, associatedLinkName, 1) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, String sessionId, String associatedLinkName, int maxMessages) { return isAuthorized(OPERATION_PEEK).thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_PEEK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBody.put(ManagementConstants.MESSAGE_COUNT_KEY, maxMessages); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, message, null); }).flatMapMany(response -> { final List<ServiceBusReceivedMessage> messages = messageSerializer.deserializeList(response, ServiceBusReceivedMessage.class); return Flux.fromIterable(messages); })); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(ServiceBusReceiveMode receiveMode, String sessionId, String associatedLinkName, Iterable<Long> sequenceNumbers) { if (sequenceNumbers == null) { return fluxError(logger, new NullPointerException("'sequenceNumbers' cannot be null")); } final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); if (numbers.isEmpty()) { return Flux.empty(); } return isAuthorized(ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER) .thenMany(createChannel.flatMap(channel -> { final Message message = createManagementMessage( ManagementConstants.OPERATION_RECEIVE_BY_SEQUENCE_NUMBER, associatedLinkName); final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.SEQUENCE_NUMBERS, numbers.toArray(new Long[0])); requestBodyMap.put(ManagementConstants.RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBodyMap.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return sendWithVerify(channel, message, null); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); return Flux.fromIterable(messageList); })); } private Throwable mapError(Throwable throwable) { if (throwable instanceof AmqpException) { return new ServiceBusException(throwable, ServiceBusErrorSource.MANAGEMENT); } return throwable; } /** * {@inheritDoc} */ @Override public Mono<OffsetDateTime> renewMessageLock(String lockToken, String associatedLinkName) { return isAuthorized(OPERATION_PEEK).then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage(ManagementConstants.OPERATION_RENEW_LOCK, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, new UUID[]{UUID.fromString(lockToken)}); requestMessage.setBody(new AmqpValue(requestBody)); return sendWithVerify(channel, requestMessage, null); }).map(responseMessage -> { final List<OffsetDateTime> renewTimeList = messageSerializer.deserializeList(responseMessage, OffsetDateTime.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Service bus response empty. Could not renew message with lock token: '%s'.", lockToken), getErrorContext()))); } return renewTimeList.get(0); })); } @Override public Mono<OffsetDateTime> renewSessionLock(String sessionId, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_RENEW_SESSION_LOCK).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_RENEW_SESSION_LOCK, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).map(response -> { final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), getErrorContext()))); } @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) value; final Object expirationValue = map.get(ManagementConstants.EXPIRATION); if (!(expirationValue instanceof Date)) { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(false, String.format( "Expiration is not of type Date when renewing session. Id: %s. Value: %s", sessionId, expirationValue), getErrorContext()))); } return ((Date) expirationValue).toInstant().atOffset(ZoneOffset.UTC); }); } /** * {@inheritDoc} */ @Override public Flux<Long> schedule(List<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, int maxLinkSize, String associatedLinkName, ServiceBusTransactionContext transactionContext) { return isAuthorized(OPERATION_SCHEDULE_MESSAGE).thenMany(createChannel.flatMap(channel -> { final Collection<Map<String, Object>> messageList = new LinkedList<>(); for (ServiceBusMessage message : messages) { message.setScheduledEnqueueTime(scheduledEnqueueTime); final Message amqpMessage = messageSerializer.serialize(message); final int payloadSize = messageSerializer.getSize(amqpMessage); final int allocationSize = Math.min(payloadSize + ManagementConstants.MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxLinkSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = amqpMessage.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format( "Error sending. Size of the payload exceeded maximum message size: %s kb", maxLinkSize / 1024); final AmqpErrorContext errorContext = channel.getErrorContext(); return monoError(logger, Exceptions.propagate(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, errorContext))); } final Map<String, Object> messageEntry = new HashMap<>(); messageEntry.put(ManagementConstants.MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(ManagementConstants.MESSAGE_ID, amqpMessage.getMessageId()); final String sessionId = amqpMessage.getGroupId(); if (!CoreUtils.isNullOrEmpty(sessionId)) { messageEntry.put(ManagementConstants.SESSION_ID, sessionId); } final String partitionKey = message.getPartitionKey(); if (!CoreUtils.isNullOrEmpty(partitionKey)) { messageEntry.put(ManagementConstants.PARTITION_KEY, partitionKey); } messageList.add(messageEntry); } final Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(ManagementConstants.MESSAGES, messageList); final Message requestMessage = createManagementMessage(OPERATION_SCHEDULE_MESSAGE, associatedLinkName); requestMessage.setBody(new AmqpValue(requestBodyMap)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, requestMessage, transactionalState); }) .flatMapMany(response -> { final List<Long> sequenceNumbers = messageSerializer.deserializeList(response, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumbers)) { fluxError(logger, new AmqpException(false, String.format( "Service Bus response was empty. Could not schedule message()s."), getErrorContext())); } return Flux.fromIterable(sequenceNumbers); })); } @Override public Mono<Void> setSessionState(String sessionId, byte[] state, String associatedLinkName) { if (sessionId == null) { return monoError(logger, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(logger, new IllegalArgumentException("'sessionId' cannot be blank.")); } return isAuthorized(OPERATION_SET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_SET_SESSION_STATE, associatedLinkName); final Map<String, Object> body = new HashMap<>(); body.put(ManagementConstants.SESSION_ID, sessionId); body.put(ManagementConstants.SESSION_STATE, state == null ? null : new Binary(state)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null).then(); })); } @Override public Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String sessionId, String associatedLinkName, ServiceBusTransactionContext transactionContext) { final UUID[] lockTokens = new UUID[]{UUID.fromString(lockToken)}; return isAuthorized(OPERATION_UPDATE_DISPOSITION).then(createChannel.flatMap(channel -> { logger.atVerbose() .addKeyValue("lockTokens", Arrays.toString(lockTokens)) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .addKeyValue(SESSION_ID_KEY, sessionId) .log("Update disposition of deliveries."); final Message message = createManagementMessage(OPERATION_UPDATE_DISPOSITION, associatedLinkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } if (!CoreUtils.isNullOrEmpty(sessionId)) { requestBody.put(ManagementConstants.SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBody)); TransactionalState transactionalState = null; if (transactionContext != null && transactionContext.getTransactionId() != null) { transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionContext.getTransactionId())); } return sendWithVerify(channel, message, transactionalState); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> createRule(String ruleName, CreateRuleOptions ruleOptions) { return isAuthorized(OPERATION_ADD_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_ADD_RULE, null); final Map<String, Object> body = new HashMap<>(2); body.put(ManagementConstants.RULE_NAME, ruleName); body.put(ManagementConstants.RULE_DESCRIPTION, MessageUtils.encodeRuleOptionToMap(ruleName, ruleOptions)); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Void> deleteRule(String ruleName) { return isAuthorized(OPERATION_REMOVE_RULE).then(createChannel.flatMap(channel -> { final Message message = createManagementMessage(OPERATION_REMOVE_RULE, null); final Map<String, Object> body = new HashMap<>(1); body.put(ManagementConstants.RULE_NAME, ruleName); message.setBody(new AmqpValue(body)); return sendWithVerify(channel, message, null); })).then(); } /** * {@inheritDoc} */ @Override public Flux<RuleProperties> getRules() { )).flatMapMany(response -> { AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(response); List<RuleProperties> list; if (statusCode == AmqpResponseCode.OK) { list = getRuleProperties((AmqpValue) response.getBody()); } else if (statusCode == AmqpResponseCode.NO_CONTENT) { list = Collections.emptyList(); } else { throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, "Get rules response error. Could not get rules.", getErrorContext()))); } return Flux.fromIterable(list); }); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } private Mono<Message> sendWithVerify(RequestResponseChannel channel, Message message, DeliveryState deliveryState) { return channel.sendWithAck(message, deliveryState) .handle((Message response, SynchronousSink<Message> sink) -> { if (RequestResponseUtils.isSuccessful(response)) { sink.next(response); return; } final AmqpResponseCode statusCode = RequestResponseUtils.getStatusCode(response); if (statusCode == AmqpResponseCode.NO_CONTENT) { sink.next(response); return; } final String errorCondition = RequestResponseUtils.getErrorCondition(response); if (statusCode == AmqpResponseCode.NOT_FOUND) { final AmqpErrorCondition amqpErrorCondition = AmqpErrorCondition.fromString(errorCondition); if (amqpErrorCondition == AmqpErrorCondition.MESSAGE_NOT_FOUND) { logger.info("There was no matching message found."); sink.next(response); return; } else if (amqpErrorCondition == AmqpErrorCondition.SESSION_NOT_FOUND) { logger.info("There was no matching session found."); sink.next(response); return; } } final String statusDescription = RequestResponseUtils.getStatusDescription(response); final Throwable throwable = ExceptionUtil.toException(errorCondition, statusDescription, channel.getErrorContext()); logger.atWarning() .addKeyValue("status", statusCode) .addKeyValue("description", statusDescription) .addKeyValue("condition", errorCondition) .log("Operation not successful."); sink.error(throwable); }) .switchIfEmpty(Mono.error(new AmqpException(true, "No response received from management channel.", channel.getErrorContext()))) .onErrorMap(this::mapError); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults() .onErrorMap(this::mapError) .next() .handle((response, sink) -> { if (response != AmqpResponseCode.ACCEPTED && response != AmqpResponseCode.OK) { final String message = String.format("User does not have authorization to perform operation " + "[%s] on entity [%s]. Response: [%s]", operation, entityPath, response); final Throwable exc = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, message, getErrorContext()); sink.error(new ServiceBusException(exc, ServiceBusErrorSource.MANAGEMENT)); } else { sink.complete(); } }); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param associatedLinkName Name of the open receive link that first received the message. * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String associatedLinkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(ManagementConstants.MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(ManagementConstants.SERVER_TIMEOUT, serverTimeout.toMillis()); if (!CoreUtils.isNullOrEmpty(associatedLinkName)) { applicationProperties.put(ManagementConstants.ASSOCIATED_LINK_NAME_KEY, associatedLinkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * Get {@link RuleProperties} from message body. * * @param messageBody A message body which is {@link AmqpValue} type. * @return A collection of {@link RuleProperties}. * * @throws UnsupportedOperationException if client cannot support filter with descriptor in message body. */ private List<RuleProperties> getRuleProperties(AmqpValue messageBody) { if (messageBody == null) { return Collections.emptyList(); } @SuppressWarnings("unchecked") List<Map<String, DescribedType>> rules = ((Map<String, List<Map<String, DescribedType>>>) messageBody.getValue()) .get(ManagementConstants.RULES); if (rules == null) { return Collections.emptyList(); } List<RuleProperties> ruleProperties = new ArrayList<>(); for (Map<String, DescribedType> rule : rules) { DescribedType ruleDescription = rule.get(ManagementConstants.RULE_DESCRIPTION); ruleProperties.add(MessageUtils.decodeRuleDescribedType(ruleDescription)); } return ruleProperties; } }
Yeah, these two util functions are copied from Track 1 SDK, I'll do a better pattern and remove hardcode.
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
if (countCorrelationFilter-- > 0) {
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
You can wait for more inputs from Connie or Srikanta before any change, as the coding style is highly opinionated, and they might not agree with me (or maybe performance here is more important than style).
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
if (countCorrelationFilter-- > 0) {
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
I think "createRule" aligns with the operation better.
private Mono<Void> createRuleInternal(String ruleName, CreateRuleOptions options) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "addRule") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.createRule(ruleName, options)); }
String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "addRule")
private Mono<Void> createRuleInternal(String ruleName, CreateRuleOptions options) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "createRule") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.createRule(ruleName, options)); }
class ServiceBusRuleManagerAsyncClient implements AutoCloseable { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusRuleManagerAsyncClient.class); private final String entityPath; private final MessagingEntityType entityType; private final ServiceBusConnectionProcessor connectionProcessor; private final Runnable onClientClose; private final AtomicBoolean isDisposed = new AtomicBoolean(); /** * Creates a rule manager that manages rules for a Service Bus subscription. * * @param entityPath The name of the topic and subscription. * @param entityType The type of the Service Bus resource. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param onClientClose Operation to run when the client completes. */ ServiceBusRuleManagerAsyncClient(String entityPath, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, Runnable onClientClose) { this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = entityType; this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityPath; } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param options The options for the rule to add. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code options}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string, action of {@code options} is not null and not * instanceof {@link SqlRuleAction}, filter of {@code options} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, CreateRuleOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } return createRuleInternal(ruleName, options); } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param filter The filter expression against which messages will be matched. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code filter}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if ruleName is empty string, {@code filter} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, RuleFilter filter) { CreateRuleOptions options = new CreateRuleOptions(filter); return createRuleInternal(ruleName, options); } /** * Fetches all rules associated with the topic and subscription. * * @return A list of rules associated with the topic and subscription. * * @throws IllegalStateException if client is disposed. */ public Mono<List<RuleProperties>> getRules() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules") )); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::getRules); } /** * Removes the rule on the subscription identified by {@code ruleName}. * * @param ruleName Name of rule to delete. * @return A Mono that completes when the rule is deleted. * * @throws NullPointerException if {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string. * @throws ServiceBusException if cannot find filter matches {@code ruleName} in subscription. */ public Mono<Void> deleteRule(String ruleName) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.deleteRule(ruleName)); } /** * Disposes of the {@link ServiceBusRuleManagerAsyncClient}. If the client has a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } }
class ServiceBusRuleManagerAsyncClient implements AutoCloseable { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusRuleManagerAsyncClient.class); private final String entityPath; private final MessagingEntityType entityType; private final ServiceBusConnectionProcessor connectionProcessor; private final Runnable onClientClose; private final AtomicBoolean isDisposed = new AtomicBoolean(); /** * Creates a rule manager that manages rules for a Service Bus subscription. * * @param entityPath The name of the topic and subscription. * @param entityType The type of the Service Bus resource. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param onClientClose Operation to run when the client completes. */ ServiceBusRuleManagerAsyncClient(String entityPath, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, Runnable onClientClose) { this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityPath; } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param options The options for the rule to add. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code options}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string, action of {@code options} is not null and not * instanceof {@link SqlRuleAction}, filter of {@code options} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, CreateRuleOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } return createRuleInternal(ruleName, options); } /** * Creates a rule to the current subscription to filter the messages reaching from topic to the subscription. * * @param ruleName Name of rule. * @param filter The filter expression against which messages will be matched. * @return A Mono that completes when the rule is created. * * @throws NullPointerException if {@code filter}, {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if ruleName is empty string, {@code filter} is not instanceof {@link SqlRuleFilter} or * {@link CorrelationRuleFilter}. * @throws ServiceBusException if filter matches {@code ruleName} is already created in subscription. */ public Mono<Void> createRule(String ruleName, RuleFilter filter) { CreateRuleOptions options = new CreateRuleOptions(filter); return createRuleInternal(ruleName, options); } /** * Fetches all rules associated with the topic and subscription. * * @return A list of rules associated with the topic and subscription. * * @throws IllegalStateException if client is disposed. * @throws UnsupportedOperationException if client cannot support filter with descriptor in message body. */ public Flux<RuleProperties> getRules() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "getRules") )); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(ServiceBusManagementNode::getRules); } /** * Removes the rule on the subscription identified by {@code ruleName}. * * @param ruleName Name of rule to delete. * @return A Mono that completes when the rule is deleted. * * @throws NullPointerException if {@code ruleName} is null. * @throws IllegalStateException if client is disposed. * @throws IllegalArgumentException if {@code ruleName} is empty string. * @throws ServiceBusException if cannot find filter matches {@code ruleName} in subscription. */ public Mono<Void> deleteRule(String ruleName) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RULE_MANAGER, "deleteRule") )); } if (ruleName == null) { return monoError(LOGGER, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(managementNode -> managementNode.deleteRule(ruleName)); } /** * Disposes of the {@link ServiceBusRuleManagerAsyncClient}. If the client has a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } }
I agree with weidong, this is a bit hard to follow.
public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; }
}
public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; } /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; } /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
I agree with weidong on this. It is a bit hard to follow.
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME)) { ArrayList<Object> describedSqlFilter = (ArrayList<Object>) describedFilter.getDescribed(); if (describedSqlFilter.size() > 0) { return new SqlRuleFilter((String) describedSqlFilter.get(0)); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME)) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); ArrayList<Object> describedCorrelationFilter = (ArrayList<Object>) describedFilter.getDescribed(); int countCorrelationFilter = describedCorrelationFilter.size(); if (countCorrelationFilter-- > 0) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.get(0))); } if (countCorrelationFilter-- > 0) { correlationFilter.setMessageId((String) (describedCorrelationFilter.get(1))); } if (countCorrelationFilter-- > 0) { correlationFilter.setTo((String) (describedCorrelationFilter.get(2))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.get(3))); } if (countCorrelationFilter-- > 0) { correlationFilter.setLabel((String) (describedCorrelationFilter.get(4))); } if (countCorrelationFilter-- > 0) { correlationFilter.setSessionId((String) (describedCorrelationFilter.get(5))); } if (countCorrelationFilter-- > 0) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.get(6))); } if (countCorrelationFilter-- > 0) { correlationFilter.setContentType((String) (describedCorrelationFilter.get(7))); } if (countCorrelationFilter > 0) { Object properties = describedCorrelationFilter.get(8); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client doesn't support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
if (countCorrelationFilter-- > 0) {
private static RuleFilter decodeFilter(DescribedType describedFilter) { if (describedFilter.getDescriptor().equals(ServiceBusConstants.SQL_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { Iterator<Object> describedSqlFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedSqlFilter.hasNext()) { return new SqlRuleFilter((String) describedSqlFilter.next()); } } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.CORRELATION_FILTER_NAME) && describedFilter.getDescribed() instanceof Iterable) { CorrelationRuleFilter correlationFilter = new CorrelationRuleFilter(); Iterator<Object> describedCorrelationFilter = ((Iterable<Object>) describedFilter.getDescribed()).iterator(); if (describedCorrelationFilter.hasNext()) { correlationFilter.setCorrelationId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setMessageId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyTo((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setLabel((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setReplyToSessionId((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { correlationFilter.setContentType((String) (describedCorrelationFilter.next())); } if (describedCorrelationFilter.hasNext()) { Object properties = describedCorrelationFilter.next(); if (properties instanceof Map) { correlationFilter.getProperties().putAll((Map<String, ?>) properties); } } return correlationFilter; } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.TRUE_FILTER_NAME)) { return new TrueRuleFilter(); } else if (describedFilter.getDescriptor().equals(ServiceBusConstants.FALSE_FILTER_NAME)) { return new FalseRuleFilter(); } else { throw new UnsupportedOperationException("This client cannot support filter with descriptor: " + describedFilter.getDescriptor()); } return null; }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Used in ServiceBusMessageBatch.tryAddMessage() to start tracing for to-be-sent out messages. */ public static ServiceBusMessage traceMessageSpan(ServiceBusMessage serviceBusMessage, Context messageContext, String hostname, String entityPath, TracerProvider tracerProvider) { Optional<Object> eventContextData = messageContext.getData(SPAN_CONTEXT_KEY); if (eventContextData.isPresent()) { return serviceBusMessage; } else { Context newMessageContext = messageContext .addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(ENTITY_PATH_KEY, entityPath) .addData(HOST_NAME_KEY, hostname); Context eventSpanContext = tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, newMessageContext, ProcessKind.MESSAGE); Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { serviceBusMessage.getApplicationProperties().put(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get() .toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); serviceBusMessage.addContext(SPAN_CONTEXT_KEY, eventSpanContext); } } return serviceBusMessage; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { HashMap<String, Object> descriptionMap = new HashMap<>(); if (options.getFilter() instanceof SqlRuleFilter) { HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); HashMap<String, Object> filterMap = new HashMap<>(); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { HashMap<String, Object> sqlActionMap = new HashMap<>(); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get message status from application properties. * * @param properties The application properties from message. * @return Status code. */ public static int getMessageStatus(ApplicationProperties properties) { int statusCode = ManagementConstants.UNDEFINED_STATUS_CODE; if (properties.getValue() == null) { return statusCode; } Object codeObject = properties.getValue().get(ManagementConstants.STATUS_CODE); if (codeObject == null) { codeObject = properties.getValue().get(ManagementConstants.LEGACY_STATUS_CODE); } if (codeObject != null) { statusCode = (int) codeObject; } return statusCode; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ @SuppressWarnings("unchecked") public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleProperties ruleProperties = new RuleProperties(); if (ruleDescribedType.getDescribed() instanceof ArrayList) { ArrayList<Object> describedRule = (ArrayList<Object>) ruleDescribedType.getDescribed(); int count = describedRule.size(); if (count-- > 0) { ruleProperties.setFilter(decodeFilter((DescribedType) describedRule.get(0))); } if (count-- > 0) { ruleProperties.setAction(decodeRuleAction((DescribedType) describedRule.get(1))); } if (count > 0) { ruleProperties.setName((String) describedRule.get(2)); } } return ruleProperties; } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ @SuppressWarnings("unchecked") private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME)) { ArrayList<Object> describedSqlAction = (ArrayList<Object>) describedAction.getDescribed(); if (describedSqlAction.size() > 0) { return new SqlRuleAction((String) describedSqlAction.get(0)); } } return null; } }
class MessageUtils { static final UUID ZERO_LOCK_TOKEN = new UUID(0L, 0L); static final int LOCK_TOKEN_SIZE = 16; private static final Symbol DEAD_LETTER_OPERATION = Symbol.getSymbol(AmqpConstants.VENDOR + ":dead-letter"); private static final String DEAD_LETTER_REASON = "DeadLetterReason"; private static final String DEAD_LETTER_ERROR_DESCRIPTION = "DeadLetterErrorDescription"; private static final long EPOCH_IN_DOT_NET_TICKS = 621355968000000000L; private static final int GUID_SIZE = 16; private MessageUtils() { } public static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(1000); } /** * Calculate the total time from the retry options assuming all retries are exhausted. */ public static Duration getTotalTimeout(AmqpRetryOptions retryOptions) { long tryTimeout = retryOptions.getTryTimeout().toNanos(); long maxDelay = retryOptions.getMaxDelay().toNanos(); long totalTimeout = tryTimeout; if (retryOptions.getMode() == AmqpRetryMode.FIXED) { totalTimeout += (retryOptions.getDelay().toNanos() + tryTimeout) * retryOptions.getMaxRetries(); } else { int multiplier = 1; for (int i = 0; i < retryOptions.getMaxRetries(); i++) { long retryDelay = retryOptions.getDelay().toNanos() * multiplier; if (retryDelay >= maxDelay) { retryDelay = maxDelay; totalTimeout += (tryTimeout + retryDelay) * (retryOptions.getMaxRetries() - i); break; } multiplier *= 2; totalTimeout += tryTimeout + retryDelay; } } return Duration.ofNanos(totalTimeout); } /** * Converts a .NET GUID to its Java UUID representation. * * @param dotNetBytes .NET GUID to convert. * * @return the equivalent UUID. */ static UUID convertDotNetBytesToUUID(byte[] dotNetBytes) { if (dotNetBytes == null || dotNetBytes.length != GUID_SIZE) { return ZERO_LOCK_TOKEN; } final byte[] reOrderedBytes = reorderBytes(dotNetBytes); final ByteBuffer buffer = ByteBuffer.wrap(reOrderedBytes); final long mostSignificantBits = buffer.getLong(); final long leastSignificantBits = buffer.getLong(); return new UUID(mostSignificantBits, leastSignificantBits); } /** * Converts a Java UUID to its byte[] representation. * * @param uuid UUID to convert to .NET bytes. * * @return The .NET byte representation. */ static byte[] convertUUIDToDotNetBytes(UUID uuid) { if (uuid == null || uuid.equals(ZERO_LOCK_TOKEN)) { return new byte[GUID_SIZE]; } ByteBuffer buffer = ByteBuffer.allocate(GUID_SIZE); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); byte[] javaBytes = buffer.array(); return reorderBytes(javaBytes); } /** * Gets the {@link OffsetDateTime} representation of .NET epoch ticks. .NET ticks are measured from 0001/01/01. * Java {@link OffsetDateTime} is measured from 1970/01/01. * * @param dotNetTicks long measured from 01/01/0001 * * @return The instant represented by the ticks. */ static OffsetDateTime convertDotNetTicksToOffsetDateTime(long dotNetTicks) { long ticksFromEpoch = dotNetTicks - EPOCH_IN_DOT_NET_TICKS; long millisecondsFromEpoch = Double.valueOf(ticksFromEpoch * 0.0001).longValue(); long fractionTicks = ticksFromEpoch % 10000; return Instant.ofEpochMilli(millisecondsFromEpoch).plusNanos(fractionTicks * 100).atOffset(ZoneOffset.UTC); } /** * Given the disposition state, returns its associated delivery state. * * @return The corresponding DeliveryState, or null if the disposition status is unknown. */ public static DeliveryState getDeliveryState(DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { boolean hasTransaction = transactionContext != null && transactionContext.getTransactionId() != null; final DeliveryState state; switch (dispositionStatus) { case COMPLETED: if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), Accepted.getInstance()); } else { state = Accepted.getInstance(); } break; case SUSPENDED: final Rejected rejected = new Rejected(); final ErrorCondition error = new ErrorCondition(DEAD_LETTER_OPERATION, null); final Map<String, Object> errorInfo = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(deadLetterReason)) { errorInfo.put(DEAD_LETTER_REASON, deadLetterReason); } if (!CoreUtils.isNullOrEmpty(deadLetterErrorDescription)) { errorInfo.put(DEAD_LETTER_ERROR_DESCRIPTION, deadLetterErrorDescription); } if (propertiesToModify != null) { errorInfo.putAll(propertiesToModify); } error.setInfo(errorInfo); rejected.setError(error); if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), rejected); } else { state = rejected; } break; case ABANDONED: final Modified outcome = new Modified(); if (propertiesToModify != null) { outcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), outcome); } else { state = outcome; } break; case DEFERRED: final Modified deferredOutcome = new Modified(); deferredOutcome.setUndeliverableHere(true); if (propertiesToModify != null) { deferredOutcome.setMessageAnnotations(propertiesToModify); } if (hasTransaction) { state = getTransactionState(transactionContext.getTransactionId(), deferredOutcome); } else { state = deferredOutcome; } break; case RELEASED: state = Released.getInstance(); break; default: state = null; } return state; } /** * Gets the primitive value or {@code false} if there is no value. * * @param value The value. * @return It's primitive type. */ public static boolean toPrimitive(Boolean value) { return value != null ? value : false; } /** * Gets the primitive value or 0 if there is no value. * * @param value The value. * @return It's primitive type. */ public static int toPrimitive(Integer value) { return value != null ? value : 0; } /** * Gets the primitive value or {@code 0L} if there is no value. * * @param value The value. * @return It's primitive type. */ public static long toPrimitive(Long value) { return value != null ? value : 0L; } private static byte[] reorderBytes(byte[] javaBytes) { byte[] reorderedBytes = new byte[GUID_SIZE]; for (int i = 0; i < GUID_SIZE; i++) { int indexInReorderedBytes; switch (i) { case 0: indexInReorderedBytes = 3; break; case 1: indexInReorderedBytes = 2; break; case 2: indexInReorderedBytes = 1; break; case 3: indexInReorderedBytes = 0; break; case 4: indexInReorderedBytes = 5; break; case 5: indexInReorderedBytes = 4; break; case 6: indexInReorderedBytes = 7; break; case 7: indexInReorderedBytes = 6; break; default: indexInReorderedBytes = i; } reorderedBytes[indexInReorderedBytes] = javaBytes[i]; } return reorderedBytes; } private static TransactionalState getTransactionState(ByteBuffer transactionId, Outcome outcome) { TransactionalState transactionalState = new TransactionalState(); transactionalState.setTxnId(Binary.create(transactionId)); transactionalState.setOutcome(outcome); return transactionalState; } /** * Convert DescribedType to origin type based on the descriptor. * @param describedType Service bus defined DescribedType. * @param <T> Including URI, OffsetDateTime and Duration * @return Original type value. */ @SuppressWarnings("unchecked") public static <T> T describedToOrigin(DescribedType describedType) { Object descriptor = describedType.getDescriptor(); Object described = describedType.getDescribed(); Objects.requireNonNull(descriptor, "descriptor of described type cannot be null."); Objects.requireNonNull(described, "described of described type cannot be null."); if (ServiceBusConstants.URI_SYMBOL.equals(descriptor)) { try { return (T) URI.create((String) described); } catch (IllegalArgumentException ex) { return (T) described; } } else if (ServiceBusConstants.OFFSETDATETIME_SYMBOL.equals(descriptor)) { long tickTime = (long) described - EPOCH_TICKS; int nano = (int) ((tickTime % TICK_PER_SECOND) * TIME_LENGTH_DELTA); long seconds = tickTime / TICK_PER_SECOND; return (T) OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nano), ZoneId.systemDefault()); } else if (ServiceBusConstants.DURATION_SYMBOL.equals(descriptor)) { return (T) Duration.ofNanos(((long) described) * TIME_LENGTH_DELTA); } return (T) described; } /** * Create a map and put {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info into map for management request. * * @param name name of rule. * @param options The options for the rule to add. * @return A map with {@link SqlRuleFilter} or {@link CorrelationRuleFilter} info to put into management message body. */ public static Map<String, Object> encodeRuleOptionToMap(String name, CreateRuleOptions options) { Map<String, Object> descriptionMap = new HashMap<>(3); if (options.getFilter() instanceof SqlRuleFilter) { Map<String, Object> filterMap = new HashMap<>(1); filterMap.put(ManagementConstants.EXPRESSION, ((SqlRuleFilter) options.getFilter()).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_FILTER, filterMap); } else if (options.getFilter() instanceof CorrelationRuleFilter) { CorrelationRuleFilter correlationFilter = (CorrelationRuleFilter) options.getFilter(); Map<String, Object> filterMap = new HashMap<>(9); filterMap.put(ManagementConstants.CORRELATION_ID, correlationFilter.getCorrelationId()); filterMap.put(ManagementConstants.MESSAGE_ID, correlationFilter.getMessageId()); filterMap.put(ManagementConstants.TO, correlationFilter.getTo()); filterMap.put(ManagementConstants.REPLY_TO, correlationFilter.getReplyTo()); filterMap.put(ManagementConstants.LABEL, correlationFilter.getLabel()); filterMap.put(ManagementConstants.SESSION_ID, correlationFilter.getSessionId()); filterMap.put(ManagementConstants.REPLY_TO_SESSION_ID, correlationFilter.getReplyToSessionId()); filterMap.put(ManagementConstants.CONTENT_TYPE, correlationFilter.getContentType()); filterMap.put(ManagementConstants.CORRELATION_FILTER_PROPERTIES, correlationFilter.getProperties()); descriptionMap.put(ManagementConstants.CORRELATION_FILTER, filterMap); } else { throw new IllegalArgumentException("This API supports the addition of only SQLFilters and CorrelationFilters."); } RuleAction action = options.getAction(); if (action == null) { descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, null); } else if (action instanceof SqlRuleAction) { Map<String, Object> sqlActionMap = new HashMap<>(1); sqlActionMap.put(ManagementConstants.EXPRESSION, ((SqlRuleAction) action).getSqlExpression()); descriptionMap.put(ManagementConstants.SQL_RULE_ACTION, sqlActionMap); } else { throw new IllegalArgumentException("This API supports the addition of only filters with SqlRuleActions."); } descriptionMap.put(ManagementConstants.RULE_NAME, name); return descriptionMap; } /** * Get {@link RuleProperties} from {@link DescribedType}. * * @param ruleDescribedType A {@link DescribedType} with rule information. * @return A {@link RuleProperties} contains name, {@link RuleAction} and {@link RuleFilter}. */ public static RuleProperties decodeRuleDescribedType(DescribedType ruleDescribedType) { if (ruleDescribedType == null) { return null; } if (!(ruleDescribedType.getDescriptor()).equals(ServiceBusConstants.RULE_DESCRIPTION_NAME)) { return null; } RuleDescription ruleDescription = new RuleDescription(); if (ruleDescribedType.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedRule = ((Iterable<Object>) ruleDescribedType.getDescribed()).iterator(); if (describedRule.hasNext()) { RuleFilter ruleFilter = decodeFilter((DescribedType) describedRule.next()); ruleDescription.setFilter(Objects.isNull(ruleFilter) ? null : EntityHelper.toImplementation(ruleFilter)); } if (describedRule.hasNext()) { RuleAction ruleAction = decodeRuleAction((DescribedType) describedRule.next()); ruleDescription.setAction(Objects.isNull(ruleAction) ? null : EntityHelper.toImplementation(ruleAction)); } if (describedRule.hasNext()) { ruleDescription.setName((String) describedRule.next()); } } return EntityHelper.toModel(ruleDescription); } /** * Get {@link RuleFilter} from a {@link DescribedType}. * * @param describedFilter A {@link DescribedType} with rule filter information. * @return A {@link RuleFilter}. */ @SuppressWarnings("unchecked") /** * Get {@link RuleAction} from a {@link DescribedType}. * * @param describedAction A {@link DescribedType} with rule action information. * @return A {@link RuleAction}. */ private static RuleAction decodeRuleAction(DescribedType describedAction) { if (describedAction.getDescriptor().equals(ServiceBusConstants.EMPTY_RULE_ACTION_NAME)) { return null; } else if (describedAction.getDescriptor().equals(ServiceBusConstants.SQL_RULE_ACTION_NAME) && describedAction.getDescribed() instanceof Iterable) { @SuppressWarnings("unchecked") Iterator<Object> describedSqlAction = ((Iterable<Object>) describedAction.getDescribed()).iterator(); if (describedSqlAction.hasNext()) { return new SqlRuleAction((String) describedSqlAction.next()); } } return null; } }
Can we please have unit tests for this logic?
private void validateReplicaAddresses(AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); List<Uri> addressesNeedToValidation = Arrays .stream(addresses) .map(address -> address.getPhysicalUri()) .filter(addressUri -> this.replicaValidationScopes.contains(addressUri.getHealthStatus())) .sorted(new Comparator<Uri>() { @Override public int compare(Uri o1, Uri o2) { return o2.getHealthStatus().getPriority() - o1.getHealthStatus().getPriority(); } }) .collect(Collectors.toList()); if (addressesNeedToValidation.size() > 0) { this.openConnectionsHandler .openConnections(addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
public int compare(Uri o1, Uri o2) {
private void validateReplicaAddresses(AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); List<Uri> addressesNeedToValidation = new ArrayList<>(); for (AddressInformation address : addresses) { if (this.replicaValidationScopes.contains(address.getPhysicalUri().getHealthStatus())) { switch (address.getPhysicalUri().getHealthStatus()) { case UnhealthyPending: addressesNeedToValidation.add(0, address.getPhysicalUri()); break; case Unknown: addressesNeedToValidation.add(address.getPhysicalUri()); break; default: throw new IllegalStateException("Validate replica status is not support for status " + address.getPhysicalUri().getHealthStatus()); } } } if (addressesNeedToValidation.size() > 0) { this.openConnectionsHandler .openConnections(addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
class GatewayAddressCache implements IAddressCache { private final static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final List<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = new ArrayList<>(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified || Arrays.stream(cachedAddresses).anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus()); }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap(addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
class GatewayAddressCache implements IAddressCache { private final static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final Set<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = ConcurrentHashMap.newKeySet(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified; }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } if (Arrays .stream(addressesValueHolder.v) .anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus())) { logger.info("refresh cache due to address uri in unhealthy status"); this.serverPartitionAddressCache.refresh( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId(request, partitionKeyRangeIdentity, true, cachedAddresses)); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap(addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
Yes, `tryGetAddress_replicaValidationTests` in GatewayAddressCacheTest has logic to validate the sequence is unhealthPending, then unkown
private void validateReplicaAddresses(AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); List<Uri> addressesNeedToValidation = Arrays .stream(addresses) .map(address -> address.getPhysicalUri()) .filter(addressUri -> this.replicaValidationScopes.contains(addressUri.getHealthStatus())) .sorted(new Comparator<Uri>() { @Override public int compare(Uri o1, Uri o2) { return o2.getHealthStatus().getPriority() - o1.getHealthStatus().getPriority(); } }) .collect(Collectors.toList()); if (addressesNeedToValidation.size() > 0) { this.openConnectionsHandler .openConnections(addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
public int compare(Uri o1, Uri o2) {
private void validateReplicaAddresses(AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); List<Uri> addressesNeedToValidation = new ArrayList<>(); for (AddressInformation address : addresses) { if (this.replicaValidationScopes.contains(address.getPhysicalUri().getHealthStatus())) { switch (address.getPhysicalUri().getHealthStatus()) { case UnhealthyPending: addressesNeedToValidation.add(0, address.getPhysicalUri()); break; case Unknown: addressesNeedToValidation.add(address.getPhysicalUri()); break; default: throw new IllegalStateException("Validate replica status is not support for status " + address.getPhysicalUri().getHealthStatus()); } } } if (addressesNeedToValidation.size() > 0) { this.openConnectionsHandler .openConnections(addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
class GatewayAddressCache implements IAddressCache { private final static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final List<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = new ArrayList<>(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified || Arrays.stream(cachedAddresses).anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus()); }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap(addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
class GatewayAddressCache implements IAddressCache { private final static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final Set<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = ConcurrentHashMap.newKeySet(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified; }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } if (Arrays .stream(addressesValueHolder.v) .anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus())) { logger.info("refresh cache due to address uri in unhealthy status"); this.serverPartitionAddressCache.refresh( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId(request, partitionKeyRangeIdentity, true, cachedAddresses)); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap(addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
Even though `refreshInProgress` might have some value in it, still the `createBackgroundRefreshTask()` will get called since it is being passed in the parameter to this `compareAndSet` function. (in java parameters are executed right to left I think). Which might be okay, since it returns a mono and nothing will happen unless we subscribe to it, but something to think about. ![image](https://user-images.githubusercontent.com/14034156/188196549-53d42249-e52b-4ac6-a4ba-86e25c23ab05.png)
public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; }
if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) {
public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
why create an extra function delegate here if we are just calling the `createRefreshFunction`? why not change it directly to below and just pass the function as it is: ``` .flatMap(createRefreshFunction) ```
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); }
.flatMap(cachedValue -> createRefreshFunction.apply(cachedValue))
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
shouldn't we change the order here as discussed offline? ``` .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); ```
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); }
this.refreshInProgress.set(null);
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
Why are we returning `Mono.empty()`? It doesn't solve any purpose. Since we have a null check above on line 137, better to return null and not execute this Mono.empty(). Currently it will consume a thread / CPU for nothing. Thoughts?
public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); }
return Mono.empty();
public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
Great documentation, good work!
public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); }
public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } }
this is error case -> we did not set the value, so there is no order to be concerned. I changed the order in the flatmap case
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); }
this.refreshInProgress.set(null);
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
yea, that also works, will update in next iterator
public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); }
return Mono.empty();
public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
make sense, will update in next iterator
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); }
.flatMap(cachedValue -> createRefreshFunction.apply(cachedValue))
private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
updated
public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; }
if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) {
public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; } public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
updated
public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return Mono.empty(); }
return Mono.empty();
public Mono<TValue> refresh(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); return this.refreshInProgress.get(); } logger.debug("Background refresh task is already in progress, skip creating a new one"); return null; }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } @SuppressWarnings("unchecked") public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { if (this.refreshInProgress.compareAndSet(null, this.createBackgroundRefreshTask(createRefreshFunction))) { logger.debug("Started a new background task"); } else { logger.debug("Background refresh task is already in progress"); } Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.get(); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(cachedValue -> createRefreshFunction.apply(cachedValue)) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { logger.warn("Background refresh task failed", throwable); this.refreshInProgress.set(null); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
class AsyncLazyWithRefresh<TValue> { private final AtomicBoolean removeFromCache = new AtomicBoolean(false); private final AtomicReference<Mono<TValue>> value; private final AtomicReference<Mono<TValue>> refreshInProgress; public AsyncLazyWithRefresh(TValue value) { this.value = new AtomicReference<>(); this.value.set(Mono.just(value)); this.refreshInProgress = new AtomicReference<>(null); } public AsyncLazyWithRefresh(Function<TValue, Mono<TValue>> taskFactory) { this.value = new AtomicReference<>(); this.value.set(taskFactory.apply(null).cache()); this.refreshInProgress = new AtomicReference<>(null); } public Mono<TValue> getValueAsync() { return this.value.get(); } public Mono<TValue> value() { return value.get(); } public Mono<TValue> getOrCreateBackgroundRefreshTaskAsync(Function<TValue, Mono<TValue>> createRefreshFunction) { Mono<TValue> refreshInProgressSnapshot = this.refreshInProgress.updateAndGet(existingMono -> { if (existingMono == null) { logger.debug("Started a new background task"); return this.createBackgroundRefreshTask(createRefreshFunction); } else { logger.debug("Background refresh task is already in progress"); } return existingMono; }); return refreshInProgressSnapshot == null ? this.value.get() : refreshInProgressSnapshot; } private Mono<TValue> createBackgroundRefreshTask(Function<TValue, Mono<TValue>> createRefreshFunction) { return this.value .get() .flatMap(createRefreshFunction) .flatMap(response -> { this.refreshInProgress.set(null); return this.value.updateAndGet(existingValue -> Mono.just(response)); }) .doOnError(throwable -> { this.refreshInProgress.set(null); logger.warn("Background refresh task failed", throwable); }) .cache(); } /*** * If there is no refresh in progress background task, then create a new one, else skip * * @param createRefreshFunction the createRefreshFunction * @return if there is already a refreshInProgress task ongoing, then return Mono.empty, else return the newly created background refresh task */ public boolean shouldRemoveFromCache() { return this.removeFromCache.compareAndSet(false, true); } }
do we have an issue tracking this we can link?
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory.createFromSecret("dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenMono = getTokenFromTargetManagedIdentity(options.getManagedIdentityType(), trc); return accessTokenMono.toFuture().thenApply(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<AccessToken> getTokenFromTargetManagedIdentity(ManagedIdentityType managedIdentityType, TokenRequestContext trc) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), trc); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), trc); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), trc); case AKS: return authenticateWithExchangeToken(trc); default: return authenticateToIMDSEndpoint(trc); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(null, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append("--tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
nit: appending Mono to the name doesn't seem to be our pattern. ```suggestion Mono<AccessToken> accessToken = getTokenFromTargetManagedIdentity(options.getManagedIdentityType(), trc); ```
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory.createFromSecret("dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenMono = getTokenFromTargetManagedIdentity(options.getManagedIdentityType(), trc); return accessTokenMono.toFuture().thenApply(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
Mono<AccessToken> accessTokenMono = getTokenFromTargetManagedIdentity(options.getManagedIdentityType(), trc);
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<AccessToken> getTokenFromTargetManagedIdentity(ManagedIdentityType managedIdentityType, TokenRequestContext trc) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), trc); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), trc); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), trc); case AKS: return authenticateWithExchangeToken(trc); default: return authenticateToIMDSEndpoint(trc); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(null, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append("--tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
Let's move `toFuture` to the end of the reactive stream. `accessTokenMono.map(accessToken -> {...}).toFuture()`
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory.createFromSecret("dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenMono = getTokenFromTargetManagedIdentity(options.getManagedIdentityType(), trc); return accessTokenMono.toFuture().thenApply(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
return accessTokenMono.toFuture().thenApply(accessToken -> {
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<AccessToken> getTokenFromTargetManagedIdentity(ManagedIdentityType managedIdentityType, TokenRequestContext trc) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), trc); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), trc); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), trc); case AKS: return authenticateWithExchangeToken(trc); default: return authenticateToIMDSEndpoint(trc); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(null, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append("--tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
it is a topic for discussion at their next meeting, Depending on outcome an issue will be created by msal team.
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory.createFromSecret("dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenMono = getTokenFromTargetManagedIdentity(options.getManagedIdentityType(), trc); return accessTokenMono.toFuture().thenApply(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<AccessToken> getTokenFromTargetManagedIdentity(ManagedIdentityType managedIdentityType, TokenRequestContext trc) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), trc); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), trc); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), trc); case AKS: return authenticateWithExchangeToken(trc); default: return authenticateToIMDSEndpoint(trc); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(null, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append("--tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
If customer cannot set it, we will need a pending task to open it for user configure in convenience code. @XiaofeiCao
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) {
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
should this be added to `IdentityConstants`?
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY"
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
This is not a valid client id, and gets used only once, we can keep it local. IdentityConstants holds valid variables currently.
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY"
private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClient() { return Mono.defer(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } if (options.getManagedIdentityType() == null) { return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available."))); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return Mono.just(confidentialClientApplication); }); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getManagedIdentityConfidentialClient()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append(" --tenant ").append(tenant); } AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = getUrl(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = getUrl(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
Is this setting the one recommended by service?
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
.withRuleSetVersion("3.0"));
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
Currently it can be se via https://github.com/Azure/azure-sdk-for-java/blob/df98d84ad0c7d90d23885d272d40b98a5393ff1b/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java#L696-L706
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) {
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
For `withRuleSetType` and `withRuleSetVersion` property, I referred to our existing code here: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ApplicationGatewayImpl.java#L703-L704 For other properties, I asked service team already, but no response from them, I will asked them again. But I tried to create an application gateway without setting WAF policy property. This is what the default property look like, so I use this as our default WAF policy. ![image](https://user-images.githubusercontent.com/87355844/183324593-64c625cf-b8e6-4879-a733-2904f4c413c7.png)
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
.withRuleSetVersion("3.0"));
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
OK, then this is good for now.
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
.withRuleSetVersion("3.0"));
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
OK, @haolingdong-msft would you update the javadoc of the `withWebApplicationFirewall` to say that it is required for `WAF_V2` (even when we provide default, we still want customer to set it)?
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) {
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
Added.
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) {
public ApplicationGatewayImpl withTier(ApplicationGatewayTier skuTier) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withTier(skuTier); if (skuTier == ApplicationGatewayTier.WAF_V2 && this.innerModel().webApplicationFirewallConfiguration() == null) { this.innerModel().withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(true) .withFirewallMode(ApplicationGatewayFirewallMode.DETECTION) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); } return this; }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
class ApplicationGatewayImpl extends GroupableParentResourceWithTagsImpl< ApplicationGateway, ApplicationGatewayInner, ApplicationGatewayImpl, NetworkManager> implements ApplicationGateway, ApplicationGateway.Definition, ApplicationGateway.Update { private Map<String, ApplicationGatewayIpConfiguration> ipConfigs; private Map<String, ApplicationGatewayFrontend> frontends; private Map<String, ApplicationGatewayProbe> probes; private Map<String, ApplicationGatewayBackend> backends; private Map<String, ApplicationGatewayBackendHttpConfiguration> backendConfigs; private Map<String, ApplicationGatewayListener> listeners; private Map<String, ApplicationGatewayRequestRoutingRule> rules; private AddedRuleCollection addedRuleCollection; private Map<String, ApplicationGatewaySslCertificate> sslCerts; private Map<String, ApplicationGatewayAuthenticationCertificate> authCertificates; private Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigs; private Map<String, ApplicationGatewayUrlPathMap> urlPathMaps; private static final String DEFAULT = "default"; private ApplicationGatewayFrontendImpl defaultPrivateFrontend; private ApplicationGatewayFrontendImpl defaultPublicFrontend; private Map<String, String> creatablePipsByFrontend; ApplicationGatewayImpl(String name, final ApplicationGatewayInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<ApplicationGateway> refreshAsync() { return super .refreshAsync() .map( applicationGateway -> { ApplicationGatewayImpl impl = (ApplicationGatewayImpl) applicationGateway; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<ApplicationGatewayInner> getInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<ApplicationGatewayInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getApplicationGateways() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override protected void initializeChildrenFromInner() { initializeConfigsFromInner(); initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeBackendHttpConfigsFromInner(); initializeHttpListenersFromInner(); initializeRedirectConfigurationsFromInner(); initializeRequestRoutingRulesFromInner(); initializeSslCertificatesFromInner(); initializeAuthCertificatesFromInner(); initializeUrlPathMapsFromInner(); this.defaultPrivateFrontend = null; this.defaultPublicFrontend = null; this.creatablePipsByFrontend = new HashMap<>(); this.addedRuleCollection = new AddedRuleCollection(); } private void initializeAuthCertificatesFromInner() { this.authCertificates = new TreeMap<>(); List<ApplicationGatewayAuthenticationCertificateInner> inners = this.innerModel().authenticationCertificates(); if (inners != null) { for (ApplicationGatewayAuthenticationCertificateInner inner : inners) { ApplicationGatewayAuthenticationCertificateImpl cert = new ApplicationGatewayAuthenticationCertificateImpl(inner, this); this.authCertificates.put(inner.name(), cert); } } } private void initializeSslCertificatesFromInner() { this.sslCerts = new TreeMap<>(); List<ApplicationGatewaySslCertificateInner> inners = this.innerModel().sslCertificates(); if (inners != null) { for (ApplicationGatewaySslCertificateInner inner : inners) { ApplicationGatewaySslCertificateImpl cert = new ApplicationGatewaySslCertificateImpl(inner, this); this.sslCerts.put(inner.name(), cert); } } } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<ApplicationGatewayFrontendIpConfiguration> inners = this.innerModel().frontendIpConfigurations(); if (inners != null) { for (ApplicationGatewayFrontendIpConfiguration inner : inners) { ApplicationGatewayFrontendImpl frontend = new ApplicationGatewayFrontendImpl(inner, this); this.frontends.put(inner.name(), frontend); } } } private void initializeProbesFromInner() { this.probes = new TreeMap<>(); List<ApplicationGatewayProbeInner> inners = this.innerModel().probes(); if (inners != null) { for (ApplicationGatewayProbeInner inner : inners) { ApplicationGatewayProbeImpl probe = new ApplicationGatewayProbeImpl(inner, this); this.probes.put(inner.name(), probe); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<ApplicationGatewayBackendAddressPool> inners = this.innerModel().backendAddressPools(); if (inners != null) { for (ApplicationGatewayBackendAddressPool inner : inners) { ApplicationGatewayBackendImpl backend = new ApplicationGatewayBackendImpl(inner, this); this.backends.put(inner.name(), backend); } } } private void initializeBackendHttpConfigsFromInner() { this.backendConfigs = new TreeMap<>(); List<ApplicationGatewayBackendHttpSettings> inners = this.innerModel().backendHttpSettingsCollection(); if (inners != null) { for (ApplicationGatewayBackendHttpSettings inner : inners) { ApplicationGatewayBackendHttpConfigurationImpl httpConfig = new ApplicationGatewayBackendHttpConfigurationImpl(inner, this); this.backendConfigs.put(inner.name(), httpConfig); } } } private void initializeHttpListenersFromInner() { this.listeners = new TreeMap<>(); List<ApplicationGatewayHttpListener> inners = this.innerModel().httpListeners(); if (inners != null) { for (ApplicationGatewayHttpListener inner : inners) { ApplicationGatewayListenerImpl httpListener = new ApplicationGatewayListenerImpl(inner, this); this.listeners.put(inner.name(), httpListener); } } } private void initializeRedirectConfigurationsFromInner() { this.redirectConfigs = new TreeMap<>(); List<ApplicationGatewayRedirectConfigurationInner> inners = this.innerModel().redirectConfigurations(); if (inners != null) { for (ApplicationGatewayRedirectConfigurationInner inner : inners) { ApplicationGatewayRedirectConfigurationImpl redirectConfig = new ApplicationGatewayRedirectConfigurationImpl(inner, this); this.redirectConfigs.put(inner.name(), redirectConfig); } } } private void initializeUrlPathMapsFromInner() { this.urlPathMaps = new TreeMap<>(); List<ApplicationGatewayUrlPathMapInner> inners = this.innerModel().urlPathMaps(); if (inners != null) { for (ApplicationGatewayUrlPathMapInner inner : inners) { ApplicationGatewayUrlPathMapImpl wrapper = new ApplicationGatewayUrlPathMapImpl(inner, this); this.urlPathMaps.put(inner.name(), wrapper); } } } private void initializeRequestRoutingRulesFromInner() { this.rules = new TreeMap<>(); List<ApplicationGatewayRequestRoutingRuleInner> inners = this.innerModel().requestRoutingRules(); if (inners != null) { for (ApplicationGatewayRequestRoutingRuleInner inner : inners) { ApplicationGatewayRequestRoutingRuleImpl rule = new ApplicationGatewayRequestRoutingRuleImpl(inner, this); this.rules.put(inner.name(), rule); } } } private void initializeConfigsFromInner() { this.ipConfigs = new TreeMap<>(); List<ApplicationGatewayIpConfigurationInner> inners = this.innerModel().gatewayIpConfigurations(); if (inners != null) { for (ApplicationGatewayIpConfigurationInner inner : inners) { ApplicationGatewayIpConfigurationImpl config = new ApplicationGatewayIpConfigurationImpl(inner, this); this.ipConfigs.put(inner.name(), config); } } } @Override protected void beforeCreating() { for (Entry<String, String> frontendPipPair : this.creatablePipsByFrontend.entrySet()) { Resource createdPip = this.<Resource>taskResult(frontendPipPair.getValue()); this.updateFrontend(frontendPipPair.getKey()).withExistingPublicIpAddress(createdPip.id()); } this.creatablePipsByFrontend.clear(); ensureDefaultIPConfig(); this.innerModel().withGatewayIpConfigurations(innersFromWrappers(this.ipConfigs.values())); this.innerModel().withFrontendIpConfigurations(innersFromWrappers(this.frontends.values())); this.innerModel().withProbes(innersFromWrappers(this.probes.values())); this.innerModel().withAuthenticationCertificates(innersFromWrappers(this.authCertificates.values())); this.innerModel().withBackendAddressPools(innersFromWrappers(this.backends.values())); this.innerModel().withSslCertificates(innersFromWrappers(this.sslCerts.values())); this.innerModel().withUrlPathMaps(innersFromWrappers(this.urlPathMaps.values())); this.innerModel().withBackendHttpSettingsCollection(innersFromWrappers(this.backendConfigs.values())); for (ApplicationGatewayBackendHttpConfiguration config : this.backendConfigs.values()) { SubResource ref; ref = config.innerModel().probe(); if (ref != null && !this.probes().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { config.innerModel().withProbe(null); } List<SubResource> certRefs = config.innerModel().authenticationCertificates(); if (certRefs != null) { certRefs = new ArrayList<>(certRefs); for (SubResource certRef : certRefs) { if (certRef != null && !this.authCertificates.containsKey(ResourceUtils.nameFromResourceId(certRef.id()))) { config.innerModel().authenticationCertificates().remove(certRef); } } } } this.innerModel().withRedirectConfigurations(innersFromWrappers(this.redirectConfigs.values())); for (ApplicationGatewayRedirectConfiguration redirect : this.redirectConfigs.values()) { SubResource ref; ref = redirect.innerModel().targetListener(); if (ref != null && !this.listeners.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { redirect.innerModel().withTargetListener(null); } } this.innerModel().withHttpListeners(innersFromWrappers(this.listeners.values())); for (ApplicationGatewayListener listener : this.listeners.values()) { SubResource ref; ref = listener.innerModel().frontendIpConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendIpConfiguration(null); } ref = listener.innerModel().frontendPort(); if (ref != null && !this.frontendPorts().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withFrontendPort(null); } ref = listener.innerModel().sslCertificate(); if (ref != null && !this.sslCertificates().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { listener.innerModel().withSslCertificate(null); } } if (supportsRulePriority()) { addedRuleCollection.autoAssignPriorities(requestRoutingRules().values(), name()); } this.innerModel().withRequestRoutingRules(innersFromWrappers(this.rules.values())); for (ApplicationGatewayRequestRoutingRule rule : this.rules.values()) { SubResource ref; ref = rule.innerModel().redirectConfiguration(); if (ref != null && !this.redirectConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withRedirectConfiguration(null); } ref = rule.innerModel().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendAddressPool(null); } ref = rule.innerModel().backendHttpSettings(); if (ref != null && !this.backendConfigs.containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withBackendHttpSettings(null); } ref = rule.innerModel().httpListener(); if (ref != null && !this.listeners().containsKey(ResourceUtils.nameFromResourceId(ref.id()))) { rule.innerModel().withHttpListener(null); } } } protected SubResource ensureBackendRef(String name) { ApplicationGatewayBackendImpl backend; if (name == null) { backend = this.ensureUniqueBackend(); } else { backend = this.defineBackend(name); backend.attach(); } return new SubResource().withId(this.futureResourceId() + "/backendAddressPools/" + backend.name()); } protected ApplicationGatewayBackendImpl ensureUniqueBackend() { String name = this.manager().resourceManager().internalContext() .randomResourceName("backend", 20); ApplicationGatewayBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } private ApplicationGatewayIpConfigurationImpl ensureDefaultIPConfig() { ApplicationGatewayIpConfigurationImpl ipConfig = (ApplicationGatewayIpConfigurationImpl) defaultIPConfiguration(); if (ipConfig == null) { String name = this.manager().resourceManager().internalContext().randomResourceName("ipcfg", 11); ipConfig = this.defineIPConfiguration(name); ipConfig.attach(); } return ipConfig; } protected ApplicationGatewayFrontendImpl ensureDefaultPrivateFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPrivateFrontend = frontend; return frontend; } } protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() { ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); if (frontend != null) { return frontend; } else { String name = this.manager().resourceManager().internalContext().randomResourceName("frontend", 14); frontend = this.defineFrontend(name); frontend.attach(); this.defaultPublicFrontend = frontend; return frontend; } } private Creatable<Network> creatableNetwork = null; private Creatable<Network> ensureDefaultNetworkDefinition() { if (this.creatableNetwork == null) { final String vnetName = this.manager().resourceManager().internalContext().randomResourceName("vnet", 10); this.creatableNetwork = this .manager() .networks() .define(vnetName) .withRegion(this.region()) .withExistingResourceGroup(this.resourceGroupName()) .withAddressSpace("10.0.0.0/24") .withSubnet(DEFAULT, "10.0.0.0/25") .withSubnet("apps", "10.0.0.128/25"); } return this.creatableNetwork; } private Creatable<PublicIpAddress> creatablePip = null; private Creatable<PublicIpAddress> ensureDefaultPipDefinition() { if (this.creatablePip == null) { final String pipName = this.manager().resourceManager().internalContext().randomResourceName("pip", 9); this.creatablePip = this .manager() .publicIpAddresses() .define(pipName) .withRegion(this.regionName()) .withExistingResourceGroup(this.resourceGroupName()); } return this.creatablePip; } private static ApplicationGatewayFrontendImpl useSubnetFromIPConfigForFrontend( ApplicationGatewayIpConfigurationImpl ipConfig, ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { frontend.withExistingSubnet(ipConfig.networkId(), ipConfig.subnetName()); if (frontend.privateIpAddress() == null) { frontend.withPrivateIpAddressDynamic(); } else if (frontend.privateIpAllocationMethod() == null) { frontend.withPrivateIpAddressDynamic(); } } return frontend; } @Override protected Mono<ApplicationGatewayInner> createInner() { final ApplicationGatewayFrontendImpl defaultPublicFrontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); final Mono<Resource> pipObservable; if (defaultPublicFrontend != null && defaultPublicFrontend.publicIpAddressId() == null) { pipObservable = ensureDefaultPipDefinition() .createAsync() .map( publicIPAddress -> { defaultPublicFrontend.withExistingPublicIpAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final ApplicationGatewayIpConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final ApplicationGatewayFrontendImpl defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) defaultPrivateFrontend(); final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { if (defaultPrivateFrontend != null) { useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } networkObservable = Mono.empty(); } else { networkObservable = ensureDefaultNetworkDefinition() .createAsync() .map( network -> { defaultIPConfig.withExistingSubnet(network, DEFAULT); if (defaultPrivateFrontend != null) { /* TODO: Not sure if the assumption of the same subnet for the frontend and * the IP config will hold in * the future, but the existing ARM template for App Gateway for some reason uses * the same subnet for the * IP config and the private frontend. Also, trying to use different subnets results * in server error today saying they * have to be the same. This may need to be revisited in the future however, * as this is somewhat inconsistent * with what the documentation says. */ useSubnetFromIPConfigForFrontend(defaultIPConfig, defaultPrivateFrontend); } return network; }); } final ApplicationGatewaysClient innerCollection = this.manager().serviceClient().getApplicationGateways(); return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap(resource -> innerCollection.createOrUpdateAsync(resourceGroupName(), name(), innerModel())); } /** * Determines whether the app gateway child that can be found using a name or a port number can be created, or it * already exists, or there is a clash. * * @param byName object found by name * @param byPort object found by port * @param name the desired name of the object * @return CreationState */ <T> CreationState needToCreate(T byName, T byPort, String name) { if (byName != null && byPort != null) { if (byName == byPort) { return CreationState.Found; } else { return CreationState.InvalidState; } } else if (byPort != null) { if (name == null) { return CreationState.Found; } else { return CreationState.InvalidState; } } else { return CreationState.NeedToCreate; } } enum CreationState { Found, NeedToCreate, InvalidState, } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/applicationGateways/") .append(this.name()) .toString(); } @Override public ApplicationGatewayImpl withDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (protocol != null) { ApplicationGatewaySslPolicy policy = ensureSslPolicy(); if (!policy.disabledSslProtocols().contains(protocol)) { policy.disabledSslProtocols().add(protocol); } } return this; } @Override public ApplicationGatewayImpl withDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { withDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocol(ApplicationGatewaySslProtocol protocol) { if (this.innerModel().sslPolicy() != null && this.innerModel().sslPolicy().disabledSslProtocols() != null) { this.innerModel().sslPolicy().disabledSslProtocols().remove(protocol); if (this.innerModel().sslPolicy().disabledSslProtocols().isEmpty()) { this.withoutAnyDisabledSslProtocols(); } } return this; } @Override public ApplicationGatewayImpl withoutDisabledSslProtocols(ApplicationGatewaySslProtocol... protocols) { if (protocols != null) { for (ApplicationGatewaySslProtocol protocol : protocols) { this.withoutDisabledSslProtocol(protocol); } } return this; } @Override public ApplicationGatewayImpl withoutAnyDisabledSslProtocols() { this.innerModel().withSslPolicy(null); return this; } @Override public ApplicationGatewayImpl withInstanceCount(int capacity) { if (this.innerModel().sku() == null) { this.withSize(ApplicationGatewaySkuName.STANDARD_SMALL); } this.innerModel().sku().withCapacity(capacity); this.innerModel().withAutoscaleConfiguration(null); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall(boolean enabled, ApplicationGatewayFirewallMode mode) { this .innerModel() .withWebApplicationFirewallConfiguration( new ApplicationGatewayWebApplicationFirewallConfiguration() .withEnabled(enabled) .withFirewallMode(mode) .withRuleSetType("OWASP") .withRuleSetVersion("3.0")); return this; } @Override public ApplicationGatewayImpl withWebApplicationFirewall( ApplicationGatewayWebApplicationFirewallConfiguration config) { this.innerModel().withWebApplicationFirewallConfiguration(config); return this; } @Override public ApplicationGatewayImpl withAutoScale(int minCapacity, int maxCapacity) { this.innerModel().sku().withCapacity(null); this .innerModel() .withAutoscaleConfiguration( new ApplicationGatewayAutoscaleConfiguration() .withMinCapacity(minCapacity) .withMaxCapacity(maxCapacity)); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressDynamic() { ensureDefaultPrivateFrontend().withPrivateIpAddressDynamic(); return this; } @Override public ApplicationGatewayImpl withPrivateIpAddressStatic(String ipAddress) { ensureDefaultPrivateFrontend().withPrivateIpAddressStatic(ipAddress); return this; } ApplicationGatewayImpl withFrontend(ApplicationGatewayFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } ApplicationGatewayImpl withProbe(ApplicationGatewayProbeImpl probe) { if (probe != null) { this.probes.put(probe.name(), probe); } return this; } ApplicationGatewayImpl withBackend(ApplicationGatewayBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } ApplicationGatewayImpl withAuthenticationCertificate(ApplicationGatewayAuthenticationCertificateImpl authCert) { if (authCert != null) { this.authCertificates.put(authCert.name(), authCert); } return this; } ApplicationGatewayImpl withSslCertificate(ApplicationGatewaySslCertificateImpl cert) { if (cert != null) { this.sslCerts.put(cert.name(), cert); } return this; } ApplicationGatewayImpl withHttpListener(ApplicationGatewayListenerImpl httpListener) { if (httpListener != null) { this.listeners.put(httpListener.name(), httpListener); } return this; } ApplicationGatewayImpl withRedirectConfiguration(ApplicationGatewayRedirectConfigurationImpl redirectConfig) { if (redirectConfig != null) { this.redirectConfigs.put(redirectConfig.name(), redirectConfig); } return this; } ApplicationGatewayImpl withUrlPathMap(ApplicationGatewayUrlPathMapImpl urlPathMap) { if (urlPathMap != null) { this.urlPathMaps.put(urlPathMap.name(), urlPathMap); } return this; } ApplicationGatewayImpl withRequestRoutingRule(ApplicationGatewayRequestRoutingRuleImpl rule) { if (rule != null) { this.rules.put(rule.name(), rule); } return this; } ApplicationGatewayImpl withBackendHttpConfiguration(ApplicationGatewayBackendHttpConfigurationImpl httpConfig) { if (httpConfig != null) { this.backendConfigs.put(httpConfig.name(), httpConfig); } return this; } @Override @Override public ApplicationGatewayImpl withSize(ApplicationGatewaySkuName skuName) { if (this.innerModel().sku() == null) { this.innerModel().withSku(new ApplicationGatewaySku().withCapacity(1)); } this.innerModel().sku().withName(skuName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Subnet subnet) { ensureDefaultIPConfig().withExistingSubnet(subnet); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(Network network, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(network, subnetName); return this; } @Override public ApplicationGatewayImpl withExistingSubnet(String networkResourceId, String subnetName) { ensureDefaultIPConfig().withExistingSubnet(networkResourceId, subnetName); return this; } @Override public ApplicationGatewayImpl withIdentity(ManagedServiceIdentity identity) { this.innerModel().withIdentity(identity); return this; } ApplicationGatewayImpl withConfig(ApplicationGatewayIpConfigurationImpl config) { if (config != null) { this.ipConfigs.put(config.name(), config); } return this; } @Override public ApplicationGatewaySslCertificateImpl defineSslCertificate(String name) { return defineChild( name, this.sslCerts, ApplicationGatewaySslCertificateInner.class, ApplicationGatewaySslCertificateImpl.class); } private ApplicationGatewayIpConfigurationImpl defineIPConfiguration(String name) { return defineChild( name, this.ipConfigs, ApplicationGatewayIpConfigurationInner.class, ApplicationGatewayIpConfigurationImpl.class); } private ApplicationGatewayFrontendImpl defineFrontend(String name) { return defineChild( name, this.frontends, ApplicationGatewayFrontendIpConfiguration.class, ApplicationGatewayFrontendImpl.class); } @Override public ApplicationGatewayRedirectConfigurationImpl defineRedirectConfiguration(String name) { return defineChild( name, this.redirectConfigs, ApplicationGatewayRedirectConfigurationInner.class, ApplicationGatewayRedirectConfigurationImpl.class); } @Override public ApplicationGatewayRequestRoutingRuleImpl defineRequestRoutingRule(String name) { ApplicationGatewayRequestRoutingRuleImpl rule = defineChild( name, this.rules, ApplicationGatewayRequestRoutingRuleInner.class, ApplicationGatewayRequestRoutingRuleImpl.class); addedRuleCollection.addRule(rule); return rule; } @Override public ApplicationGatewayBackendImpl defineBackend(String name) { return defineChild( name, this.backends, ApplicationGatewayBackendAddressPool.class, ApplicationGatewayBackendImpl.class); } @Override public ApplicationGatewayAuthenticationCertificateImpl defineAuthenticationCertificate(String name) { return defineChild( name, this.authCertificates, ApplicationGatewayAuthenticationCertificateInner.class, ApplicationGatewayAuthenticationCertificateImpl.class); } @Override public ApplicationGatewayProbeImpl defineProbe(String name) { return defineChild(name, this.probes, ApplicationGatewayProbeInner.class, ApplicationGatewayProbeImpl.class); } @Override public ApplicationGatewayUrlPathMapImpl definePathBasedRoutingRule(String name) { ApplicationGatewayUrlPathMapImpl urlPathMap = defineChild( name, this.urlPathMaps, ApplicationGatewayUrlPathMapInner.class, ApplicationGatewayUrlPathMapImpl.class); SubResource ref = new SubResource().withId(futureResourceId() + "/urlPathMaps/" + name); ApplicationGatewayRequestRoutingRuleInner inner = new ApplicationGatewayRequestRoutingRuleInner() .withName(name) .withRuleType(ApplicationGatewayRequestRoutingRuleType.PATH_BASED_ROUTING) .withUrlPathMap(ref); rules.put(name, new ApplicationGatewayRequestRoutingRuleImpl(inner, this)); return urlPathMap; } @Override public ApplicationGatewayListenerImpl defineListener(String name) { return defineChild( name, this.listeners, ApplicationGatewayHttpListener.class, ApplicationGatewayListenerImpl.class); } @Override public ApplicationGatewayBackendHttpConfigurationImpl defineBackendHttpConfiguration(String name) { ApplicationGatewayBackendHttpConfigurationImpl config = defineChild( name, this.backendConfigs, ApplicationGatewayBackendHttpSettings.class, ApplicationGatewayBackendHttpConfigurationImpl.class); if (config.innerModel().id() == null) { return config.withPort(80); } else { return config; } } @SuppressWarnings("unchecked") private <ChildImplT, ChildT, ChildInnerT> ChildImplT defineChild( String name, Map<String, ChildT> children, Class<ChildInnerT> innerClass, Class<ChildImplT> implClass) { ChildT child = children.get(name); if (child == null) { ChildInnerT inner; try { inner = innerClass.getDeclaredConstructor().newInstance(); innerClass.getDeclaredMethod("withName", String.class).invoke(inner, name); return implClass .getDeclaredConstructor(innerClass, ApplicationGatewayImpl.class) .newInstance(inner, this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { return null; } } else { return (ChildImplT) child; } } @Override public ApplicationGatewayImpl withoutPrivateFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPrivateFrontend = null; return this; } @Override public ApplicationGatewayImpl withoutPublicFrontend() { List<String> toDelete = new ArrayList<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { toDelete.add(frontend.name()); } } for (String frontendName : toDelete) { this.frontends.remove(frontendName); } this.defaultPublicFrontend = null; return this; } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber) { return withFrontendPort(portNumber, null); } @Override public ApplicationGatewayImpl withFrontendPort(int portNumber, String name) { List<ApplicationGatewayFrontendPort> frontendPorts = this.innerModel().frontendPorts(); if (frontendPorts == null) { frontendPorts = new ArrayList<ApplicationGatewayFrontendPort>(); this.innerModel().withFrontendPorts(frontendPorts); } ApplicationGatewayFrontendPort frontendPortByName = null; ApplicationGatewayFrontendPort frontendPortByNumber = null; for (ApplicationGatewayFrontendPort inner : this.innerModel().frontendPorts()) { if (name != null && name.equalsIgnoreCase(inner.name())) { frontendPortByName = inner; } if (inner.port() == portNumber) { frontendPortByNumber = inner; } } CreationState needToCreate = this.needToCreate(frontendPortByName, frontendPortByNumber, name); if (needToCreate == CreationState.NeedToCreate) { if (name == null) { name = this.manager().resourceManager().internalContext().randomResourceName("port", 9); } frontendPortByName = new ApplicationGatewayFrontendPort().withName(name).withPort(portNumber); frontendPorts.add(frontendPortByName); return this; } else if (needToCreate == CreationState.Found) { return this; } else { return null; } } @Override public ApplicationGatewayImpl withPrivateFrontend() { /* NOTE: This logic is a workaround for the unusual Azure API logic: * - although app gateway API definition allows multiple IP configs, * only one is allowed by the service currently; * - although app gateway frontend API definition allows for multiple frontends, * only one is allowed by the service today; * - and although app gateway API definition allows different subnets to be specified * between the IP configs and frontends, the service * requires the frontend and the containing subnet to be one and the same currently. * * So the logic here attempts to figure out from the API what that containing subnet * for the app gateway is so that the user wouldn't have to re-enter it redundantly * when enabling a private frontend, since only that one subnet is supported anyway. * * TODO: When the underlying Azure API is reworked to make more sense, * or the app gateway service starts supporting the functionality * that the underlying API implies is supported, this model and implementation should be revisited. */ ensureDefaultPrivateFrontend(); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(PublicIpAddress publicIPAddress) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(publicIPAddress); return this; } @Override public ApplicationGatewayImpl withExistingPublicIpAddress(String resourceId) { ensureDefaultPublicFrontend().withExistingPublicIpAddress(resourceId); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress(Creatable<PublicIpAddress> creatable) { final String name = ensureDefaultPublicFrontend().name(); this.creatablePipsByFrontend.put(name, this.addDependency(creatable)); return this; } @Override public ApplicationGatewayImpl withNewPublicIpAddress() { ensureDefaultPublicFrontend(); return this; } @Override public ApplicationGatewayImpl withoutBackendFqdn(String fqdn) { for (ApplicationGatewayBackend backend : this.backends.values()) { ((ApplicationGatewayBackendImpl) backend).withoutFqdn(fqdn); } return this; } @Override public ApplicationGatewayImpl withoutBackendIPAddress(String ipAddress) { for (ApplicationGatewayBackend backend : this.backends.values()) { ApplicationGatewayBackendImpl backendImpl = (ApplicationGatewayBackendImpl) backend; backendImpl.withoutIPAddress(ipAddress); } return this; } @Override public ApplicationGatewayImpl withoutIPConfiguration(String ipConfigurationName) { this.ipConfigs.remove(ipConfigurationName); return this; } @Override public ApplicationGatewayImpl withoutFrontend(String frontendName) { this.frontends.remove(frontendName); return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(String name) { if (this.innerModel().frontendPorts() == null) { return this; } for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.name().equalsIgnoreCase(name)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutFrontendPort(int portNumber) { for (int i = 0; i < this.innerModel().frontendPorts().size(); i++) { ApplicationGatewayFrontendPort inner = this.innerModel().frontendPorts().get(i); if (inner.port().equals(portNumber)) { this.innerModel().frontendPorts().remove(i); break; } } return this; } @Override public ApplicationGatewayImpl withoutSslCertificate(String name) { this.sslCerts.remove(name); return this; } @Override public ApplicationGatewayImpl withoutAuthenticationCertificate(String name) { this.authCertificates.remove(name); return this; } @Override public ApplicationGatewayImpl withoutProbe(String name) { this.probes.remove(name); return this; } @Override public ApplicationGatewayImpl withoutListener(String name) { this.listeners.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRedirectConfiguration(String name) { this.redirectConfigs.remove(name); return this; } @Override public ApplicationGatewayImpl withoutUrlPathMap(String name) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { if (rule.urlPathMap() != null && name.equals(rule.urlPathMap().name())) { rules.remove(rule.name()); break; } } this.urlPathMaps.remove(name); return this; } @Override public ApplicationGatewayImpl withoutRequestRoutingRule(String name) { this.rules.remove(name); this.addedRuleCollection.removeRule(name); return this; } @Override public ApplicationGatewayImpl withoutBackend(String backendName) { this.backends.remove(backendName); return this; } @Override public ApplicationGatewayImpl withHttp2() { innerModel().withEnableHttp2(true); return this; } @Override public ApplicationGatewayImpl withoutHttp2() { innerModel().withEnableHttp2(false); return this; } @Override public ApplicationGatewayImpl withAvailabilityZone(AvailabilityZoneId zoneId) { if (this.innerModel().zones() == null) { this.innerModel().withZones(new ArrayList<String>()); } if (!this.innerModel().zones().contains(zoneId.toString())) { this.innerModel().zones().add(zoneId.toString()); } return this; } @Override public ApplicationGatewayBackendImpl updateBackend(String name) { return (ApplicationGatewayBackendImpl) this.backends.get(name); } @Override public ApplicationGatewayFrontendImpl updatePublicFrontend() { return (ApplicationGatewayFrontendImpl) defaultPublicFrontend(); } @Override public ApplicationGatewayListenerImpl updateListener(String name) { return (ApplicationGatewayListenerImpl) this.listeners.get(name); } @Override public ApplicationGatewayRedirectConfigurationImpl updateRedirectConfiguration(String name) { return (ApplicationGatewayRedirectConfigurationImpl) this.redirectConfigs.get(name); } @Override public ApplicationGatewayRequestRoutingRuleImpl updateRequestRoutingRule(String name) { return (ApplicationGatewayRequestRoutingRuleImpl) this.rules.get(name); } @Override public ApplicationGatewayImpl withoutBackendHttpConfiguration(String name) { this.backendConfigs.remove(name); return this; } @Override public ApplicationGatewayBackendHttpConfigurationImpl updateBackendHttpConfiguration(String name) { return (ApplicationGatewayBackendHttpConfigurationImpl) this.backendConfigs.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateIPConfiguration(String ipConfigurationName) { return (ApplicationGatewayIpConfigurationImpl) this.ipConfigs.get(ipConfigurationName); } @Override public ApplicationGatewayProbeImpl updateProbe(String name) { return (ApplicationGatewayProbeImpl) this.probes.get(name); } @Override public ApplicationGatewayIpConfigurationImpl updateDefaultIPConfiguration() { return (ApplicationGatewayIpConfigurationImpl) this.defaultIPConfiguration(); } @Override public ApplicationGatewayIpConfigurationImpl defineDefaultIPConfiguration() { return ensureDefaultIPConfig(); } @Override public ApplicationGatewayFrontendImpl definePublicFrontend() { return ensureDefaultPublicFrontend(); } @Override public ApplicationGatewayFrontendImpl definePrivateFrontend() { return ensureDefaultPrivateFrontend(); } @Override public ApplicationGatewayFrontendImpl updateFrontend(String frontendName) { return (ApplicationGatewayFrontendImpl) this.frontends.get(frontendName); } @Override public ApplicationGatewayUrlPathMapImpl updateUrlPathMap(String name) { return (ApplicationGatewayUrlPathMapImpl) this.urlPathMaps.get(name); } @Override public Collection<ApplicationGatewaySslProtocol> disabledSslProtocols() { if (this.innerModel().sslPolicy() == null || this.innerModel().sslPolicy().disabledSslProtocols() == null) { return new ArrayList<>(); } else { return Collections.unmodifiableCollection(this.innerModel().sslPolicy().disabledSslProtocols()); } } @Override public ApplicationGatewayFrontend defaultPrivateFrontend() { Map<String, ApplicationGatewayFrontend> privateFrontends = this.privateFrontends(); if (privateFrontends.size() == 1) { this.defaultPrivateFrontend = (ApplicationGatewayFrontendImpl) privateFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPrivateFrontend = null; } return this.defaultPrivateFrontend; } @Override public ApplicationGatewayFrontend defaultPublicFrontend() { Map<String, ApplicationGatewayFrontend> publicFrontends = this.publicFrontends(); if (publicFrontends.size() == 1) { this.defaultPublicFrontend = (ApplicationGatewayFrontendImpl) publicFrontends.values().iterator().next(); } else if (this.frontends().size() == 0) { this.defaultPublicFrontend = null; } return this.defaultPublicFrontend; } @Override public ApplicationGatewayIpConfiguration defaultIPConfiguration() { if (this.ipConfigs.size() == 1) { return this.ipConfigs.values().iterator().next(); } else { return null; } } @Override public ApplicationGatewayListener listenerByPortNumber(int portNumber) { ApplicationGatewayListener listener = null; for (ApplicationGatewayListener l : this.listeners.values()) { if (l.frontendPortNumber() == portNumber) { listener = l; break; } } return listener; } @Override public Map<String, ApplicationGatewayAuthenticationCertificate> authenticationCertificates() { return Collections.unmodifiableMap(this.authCertificates); } @Override public boolean isHttp2Enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableHttp2()); } @Override public Map<String, ApplicationGatewayUrlPathMap> urlPathMaps() { return Collections.unmodifiableMap(this.urlPathMaps); } @Override public Set<AvailabilityZoneId> availabilityZones() { Set<AvailabilityZoneId> zones = new TreeSet<>(); if (this.innerModel().zones() != null) { for (String zone : this.innerModel().zones()) { zones.add(AvailabilityZoneId.fromString(zone)); } } return Collections.unmodifiableSet(zones); } @Override public Map<String, ApplicationGatewayBackendHttpConfiguration> backendHttpConfigurations() { return Collections.unmodifiableMap(this.backendConfigs); } @Override public Map<String, ApplicationGatewayBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, ApplicationGatewayFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, ApplicationGatewayProbe> probes() { return Collections.unmodifiableMap(this.probes); } @Override public Map<String, ApplicationGatewaySslCertificate> sslCertificates() { return Collections.unmodifiableMap(this.sslCerts); } @Override public Map<String, ApplicationGatewayListener> listeners() { return Collections.unmodifiableMap(this.listeners); } @Override public Map<String, ApplicationGatewayRedirectConfiguration> redirectConfigurations() { return Collections.unmodifiableMap(this.redirectConfigs); } @Override public Map<String, ApplicationGatewayIpConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.ipConfigs); } @Override public ApplicationGatewaySku sku() { return this.innerModel().sku(); } @Override public ApplicationGatewayOperationalState operationalState() { return this.innerModel().operationalState(); } @Override public Map<String, Integer> frontendPorts() { Map<String, Integer> ports = new TreeMap<>(); if (this.innerModel().frontendPorts() != null) { for (ApplicationGatewayFrontendPort portInner : this.innerModel().frontendPorts()) { ports.put(portInner.name(), portInner.port()); } } return Collections.unmodifiableMap(ports); } @Override public String frontendPortNameFromNumber(int portNumber) { String portName = null; for (Entry<String, Integer> portEntry : this.frontendPorts().entrySet()) { if (portNumber == portEntry.getValue()) { portName = portEntry.getKey(); break; } } return portName; } private SubResource defaultSubnetRef() { ApplicationGatewayIpConfiguration ipConfig = defaultIPConfiguration(); if (ipConfig == null) { return null; } else { return ipConfig.innerModel().subnet(); } } @Override public String networkId() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.parentResourceIdFromResourceId(subnetRef.id()); } } @Override public String subnetName() { SubResource subnetRef = defaultSubnetRef(); if (subnetRef == null) { return null; } else { return ResourceUtils.nameFromResourceId(subnetRef.id()); } } @Override public String privateIpAddress() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAddress(); } } @Override public IpAllocationMethod privateIpAllocationMethod() { ApplicationGatewayFrontend frontend = defaultPrivateFrontend(); if (frontend == null) { return null; } else { return frontend.privateIpAllocationMethod(); } } @Override public boolean isPrivate() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { return true; } } return false; } @Override public boolean isPublic() { for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPublic()) { return true; } } return false; } @Override public Map<String, ApplicationGatewayFrontend> publicFrontends() { Map<String, ApplicationGatewayFrontend> publicFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, ApplicationGatewayFrontend> privateFrontends() { Map<String, ApplicationGatewayFrontend> privateFrontends = new TreeMap<>(); for (ApplicationGatewayFrontend frontend : this.frontends.values()) { if (frontend.isPrivate()) { privateFrontends.put(frontend.name(), frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public int instanceCount() { if (this.sku() != null && this.sku().capacity() != null) { return this.sku().capacity(); } else { return 1; } } @Override public ApplicationGatewaySkuName size() { if (this.sku() != null && this.sku().name() != null) { return this.sku().name(); } else { return ApplicationGatewaySkuName.STANDARD_SMALL; } } @Override public ApplicationGatewayTier tier() { if (this.sku() != null && this.sku().tier() != null) { return this.sku().tier(); } else { return ApplicationGatewayTier.STANDARD; } } @Override public ApplicationGatewayAutoscaleConfiguration autoscaleConfiguration() { return this.innerModel().autoscaleConfiguration(); } @Override public ApplicationGatewayWebApplicationFirewallConfiguration webApplicationFirewallConfiguration() { return this.innerModel().webApplicationFirewallConfiguration(); } @Override public Update withoutPublicIpAddress() { return this.withoutPublicFrontend(); } @Override public void start() { this.startAsync().block(); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> startAsync() { Mono<Void> startObservable = this.manager().serviceClient().getApplicationGateways().startAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(startObservable, refreshObservable).then(); } @Override public Mono<Void> stopAsync() { Mono<Void> stopObservable = this.manager().serviceClient().getApplicationGateways().stopAsync(this.resourceGroupName(), this.name()); Mono<ApplicationGateway> refreshObservable = refreshAsync(); return Flux.concat(stopObservable, refreshObservable).then(); } private ApplicationGatewaySslPolicy ensureSslPolicy() { ApplicationGatewaySslPolicy policy = this.innerModel().sslPolicy(); if (policy == null) { policy = new ApplicationGatewaySslPolicy(); this.innerModel().withSslPolicy(policy); } List<ApplicationGatewaySslProtocol> protocols = policy.disabledSslProtocols(); if (protocols == null) { protocols = new ArrayList<>(); policy.withDisabledSslProtocols(protocols); } return policy; } @Override public Map<String, ApplicationGatewayBackendHealth> checkBackendHealth() { return this.checkBackendHealthAsync().block(); } @Override public Mono<Map<String, ApplicationGatewayBackendHealth>> checkBackendHealthAsync() { return this .manager() .serviceClient() .getApplicationGateways() .backendHealthAsync(this.resourceGroupName(), this.name(), null) .map( inner -> { Map<String, ApplicationGatewayBackendHealth> backendHealths = new TreeMap<>(); if (inner != null) { for (ApplicationGatewayBackendHealthPool healthInner : inner.backendAddressPools()) { ApplicationGatewayBackendHealth backendHealth = new ApplicationGatewayBackendHealthImpl(healthInner, ApplicationGatewayImpl.this); backendHealths.put(backendHealth.name(), backendHealth); } } return Collections.unmodifiableMap(backendHealths); }); } /* * Only V2 Gateway supports priority. */ private boolean supportsRulePriority() { ApplicationGatewayTier tier = tier(); ApplicationGatewaySkuName sku = size(); return tier != ApplicationGatewayTier.STANDARD && sku != ApplicationGatewaySkuName.STANDARD_SMALL && sku != ApplicationGatewaySkuName.STANDARD_MEDIUM && sku != ApplicationGatewaySkuName.STANDARD_LARGE && sku != ApplicationGatewaySkuName.WAF_MEDIUM && sku != ApplicationGatewaySkuName.WAF_LARGE; } private static class AddedRuleCollection { private static final int AUTO_ASSIGN_PRIORITY_START = 10010; private static final int MAX_PRIORITY = 20000; private static final int PRIORITY_INTERVAL = 10; private final Map<String, ApplicationGatewayRequestRoutingRuleImpl> ruleMap = new LinkedHashMap<>(); /* * Remove a rule from priority auto-assignment. */ void removeRule(String name) { ruleMap.remove(name); } /* * Add a rule for priority auto-assignment while preserving the adding order. */ void addRule(ApplicationGatewayRequestRoutingRuleImpl rule) { ruleMap.put(rule.name(), rule); } /* * Auto-assign priority values for rules without priority (ranging from 10010 to 20000). * Rules defined later in the definition chain will have larger priority values over those defined earlier. */ void autoAssignPriorities(Collection<ApplicationGatewayRequestRoutingRule> existingRules, String gatewayName) { Set<Integer> existingPriorities = existingRules .stream() .map(ApplicationGatewayRequestRoutingRule::priority) .filter(Objects::nonNull) .collect(Collectors.toSet()); int nextPriorityToAssign = AUTO_ASSIGN_PRIORITY_START; for (ApplicationGatewayRequestRoutingRuleImpl rule : ruleMap.values()) { if (rule.priority() != null) { continue; } boolean assigned = false; for (int priority = nextPriorityToAssign; priority <= MAX_PRIORITY; priority += PRIORITY_INTERVAL) { if (existingPriorities.contains(priority)) { continue; } rule.withPriority(priority); assigned = true; existingPriorities.add(priority); nextPriorityToAssign = priority + PRIORITY_INTERVAL; break; } if (!assigned) { throw new IllegalStateException( String.format("Failed to auto assign priority for rule: %s, gateway: %s", rule.name(), gatewayName)); } } } } }
The pageRetriever (sync or async) will be final once this instance is created. So, we don't need to check if it's null in a `while` loop.
public boolean hasNext() { while (!done && needToRequestPage() && pageRetriever != null) { requestPage(); } while (!done && needToRequestPage() && syncPageRetriever != null) { requestPageSync(); } return isNextAvailable(); }
while (!done && needToRequestPage() && syncPageRetriever != null) {
public boolean hasNext() { while (!done && needToRequestPage()) { requestPage(); } return isNextAvailable(); }
class ContinuablePagedByIteratorBase<C, T, P extends ContinuablePage<C, T>, E> implements Iterator<E> { private final PageRetriever<C, P> pageRetriever; private final SyncPageRetriever<C, P> syncPageRetriever; private final ContinuationState<C> continuationState; private final Integer defaultPageSize; private final ClientLogger logger; private volatile boolean done; ContinuablePagedByIteratorBase(PageRetriever<C, P> pageRetriever, ContinuationState<C> continuationState, Integer defaultPageSize, ClientLogger logger) { this.continuationState = continuationState; this.pageRetriever = pageRetriever; this.defaultPageSize = defaultPageSize; this.logger = logger; this.syncPageRetriever = null; } ContinuablePagedByIteratorBase(SyncPageRetriever<C, P> syncPageRetriever, ContinuationState<C> continuationState, Integer defaultPageSize, ClientLogger logger) { this.continuationState = continuationState; this.syncPageRetriever = syncPageRetriever; this.defaultPageSize = defaultPageSize; this.logger = logger; this.pageRetriever = null; } @Override public E next() { if (!hasNext()) { throw logger.logExceptionAsError(new NoSuchElementException("Iterator contains no more elements.")); } return getNext(); } @Override /* * Indicates if a page needs to be requested. */ abstract boolean needToRequestPage(); /* * Indicates if another element is available. */ abstract boolean isNextAvailable(); /* * Gets the next element to be emitted. */ abstract E getNext(); synchronized void requestPage() { /* * In the scenario where multiple threads were waiting on synchronization, check that no earlier thread made a * request that would satisfy the current element request. Additionally, check to make sure that any earlier * requests didn't consume the paged responses to completion. */ if (isNextAvailable() || done) { return; } AtomicBoolean receivedPages = new AtomicBoolean(false); pageRetriever.get(continuationState.getLastContinuationToken(), defaultPageSize) .map(page -> { receivedPages.set(true); addPage(page); continuationState.setLastContinuationToken(page.getContinuationToken()); this.done = continuationState.isDone(); return page; }).blockLast(); /* * In the scenario when the subscription completes without emitting an element indicate we are done by checking * if we have any additional elements to return. */ this.done = done || (!receivedPages.get() && !isNextAvailable()); } synchronized void requestPageSync() { /* * In the scenario where multiple threads were waiting on synchronization, check that no earlier thread made a * request that would satisfy the current element request. Additionally, check to make sure that any earlier * requests didn't consume the paged responses to completion. */ if (isNextAvailable() || done) { return; } AtomicBoolean receivedPages = new AtomicBoolean(false); syncPageRetriever .getIterable(continuationState.getLastContinuationToken(), defaultPageSize) .forEach(page -> { receivedPages.set(true); addPage(page); continuationState.setLastContinuationToken(page.getContinuationToken()); this.done = continuationState.isDone(); }); /* * In the scenario when the subscription completes without emitting an element indicate we are done by checking * if we have any additional elements to return. */ this.done = done || (!receivedPages.get() && !isNextAvailable()); } /* * Add a page returned by the service and update the continuation state. */ abstract void addPage(P page); }
class ContinuablePagedByIteratorBase<C, T, P extends ContinuablePage<C, T>, E> implements Iterator<E> { private final PageRetriever<C, P> pageRetriever; private final PageRetrieverSync<C, P> pageRetrieverSync; private final ContinuationState<C> continuationState; private final Integer defaultPageSize; private final ClientLogger logger; private volatile boolean done; ContinuablePagedByIteratorBase(PageRetriever<C, P> pageRetriever, ContinuationState<C> continuationState, Integer defaultPageSize, ClientLogger logger) { this.continuationState = continuationState; this.pageRetriever = pageRetriever; this.defaultPageSize = defaultPageSize; this.logger = logger; this.pageRetrieverSync = null; } ContinuablePagedByIteratorBase(PageRetrieverSync<C, P> pageRetrieverSync, ContinuationState<C> continuationState, Integer defaultPageSize, ClientLogger logger) { this.continuationState = continuationState; this.pageRetrieverSync = pageRetrieverSync; this.defaultPageSize = defaultPageSize; this.logger = logger; this.pageRetriever = null; } @Override public E next() { if (!hasNext()) { throw logger.logExceptionAsError(new NoSuchElementException("Iterator contains no more elements.")); } return getNext(); } @Override /* * Indicates if a page needs to be requested. */ abstract boolean needToRequestPage(); /* * Indicates if another element is available. */ abstract boolean isNextAvailable(); /* * Gets the next element to be emitted. */ abstract E getNext(); synchronized void requestPage() { AtomicBoolean receivedPages = new AtomicBoolean(false); if (pageRetriever != null) { /* * In the scenario where multiple threads were waiting on synchronization, check that no earlier thread made a * request that would satisfy the current element request. Additionally, check to make sure that any earlier * requests didn't consume the paged responses to completion. */ if (isNextAvailable() || done) { return; } pageRetriever.get(continuationState.getLastContinuationToken(), defaultPageSize) .map(page -> { receivePage(receivedPages, page); return page; }).blockLast(); } else if (pageRetrieverSync != null) { P page = pageRetrieverSync.getPage(continuationState.getLastContinuationToken(), defaultPageSize); if (page != null) { receivePage(receivedPages, page); } } /* * In the scenario when the subscription completes without emitting an element indicate we are done by checking * if we have any additional elements to return. */ this.done = done || (!receivedPages.get() && !isNextAvailable()); } /* * Add a page returned by the service and update the continuation state. */ abstract void addPage(P page); private void receivePage(AtomicBoolean receivedPages, P page) { receivedPages.set(true); addPage(page); continuationState.setLastContinuationToken(page.getContinuationToken()); this.done = continuationState.isDone(); } }
Why do we have this check? The other overload that takes Flux<ByteBuffer> as input doesn't require length.
public FileParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data must not be null", data); StorageImplUtils.assertNotNull("data must have defined length", data.getLength()); this.data = data; this.length = data.getLength(); this.dataFlux = null; this.dataStream = null; }
StorageImplUtils.assertNotNull("data must have defined length", data.getLength());
public FileParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data must not be null", data); this.data = data; this.length = data.getLength(); this.dataFlux = null; this.dataStream = null; }
class FileParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final BinaryData data; private final Long length; private ParallelTransferOptions parallelTransferOptions; private PathHttpHeaders headers; private Map<String, String> metadata; private String permissions; private String umask; private DataLakeRequestConditions requestConditions; /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataFlux The data to write to the file. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public FileParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; this.data = null; } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param data The {@link BinaryData} to write to the file. */ /** * Constructs a new {@code FileParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public FileParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. */ public FileParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } private FileParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.length = length; this.dataFlux = null; this.data = null; } /** * Gets the data source. * * @return The data to write to the file. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the file. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the data source. * * @return The data to write to the file. */ public BinaryData getData() { return this.data; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated public long getLength() { return length; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public FileParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link PathHttpHeaders}. * * @return {@link PathHttpHeaders} */ public PathHttpHeaders getHeaders() { return headers; } /** * Sets the {@link PathHttpHeaders}. * * @param headers {@link PathHttpHeaders} * @return The updated options */ public FileParallelUploadOptions setHeaders(PathHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the file. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public FileParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the permissions. * * @return the POSIX access permissions for the resource owner, the resource owning group, and others. */ public String getPermissions() { return permissions; } /** * Sets the permissions. * * @param permissions the POSIX access permissions for the resource owner, the resource owning group, and others. * @return The updated options */ public FileParallelUploadOptions setPermissions(String permissions) { this.permissions = permissions; return this; } /** * Gets the umask. * * @return the umask. */ public String getUmask() { return umask; } /** * Sets the umask. * * @param umask Restricts permissions of the resource to be created. * @return The updated options */ public FileParallelUploadOptions setUmask(String umask) { this.umask = umask; return this; } /** * Gets the {@link DataLakeRequestConditions}. * * @return {@link DataLakeRequestConditions} */ public DataLakeRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link DataLakeRequestConditions}. * * @param requestConditions {@link DataLakeRequestConditions} * @return The updated options. */ public FileParallelUploadOptions setRequestConditions(DataLakeRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } }
class FileParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final BinaryData data; private final Long length; private ParallelTransferOptions parallelTransferOptions; private PathHttpHeaders headers; private Map<String, String> metadata; private String permissions; private String umask; private DataLakeRequestConditions requestConditions; /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataFlux The data to write to the file. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public FileParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; this.data = null; } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param data The {@link BinaryData} to write to the file. */ /** * Constructs a new {@code FileParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public FileParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. */ public FileParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } private FileParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.length = length; this.dataFlux = null; this.data = null; } /** * Gets the data source. * * @return The data to write to the file. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the file. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the data source. * * @return The data to write to the file. */ public BinaryData getData() { return this.data; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated public long getLength() { return length; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public FileParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link PathHttpHeaders}. * * @return {@link PathHttpHeaders} */ public PathHttpHeaders getHeaders() { return headers; } /** * Sets the {@link PathHttpHeaders}. * * @param headers {@link PathHttpHeaders} * @return The updated options */ public FileParallelUploadOptions setHeaders(PathHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the file. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public FileParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the permissions. * * @return the POSIX access permissions for the resource owner, the resource owning group, and others. */ public String getPermissions() { return permissions; } /** * Sets the permissions. * * @param permissions the POSIX access permissions for the resource owner, the resource owning group, and others. * @return The updated options */ public FileParallelUploadOptions setPermissions(String permissions) { this.permissions = permissions; return this; } /** * Gets the umask. * * @return the umask. */ public String getUmask() { return umask; } /** * Sets the umask. * * @param umask Restricts permissions of the resource to be created. * @return The updated options */ public FileParallelUploadOptions setUmask(String umask) { this.umask = umask; return this; } /** * Gets the {@link DataLakeRequestConditions}. * * @return {@link DataLakeRequestConditions} */ public DataLakeRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link DataLakeRequestConditions}. * * @param requestConditions {@link DataLakeRequestConditions} * @return The updated options. */ public FileParallelUploadOptions setRequestConditions(DataLakeRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } }
Good catch, I'll remove this check since not needed.
public FileParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data must not be null", data); StorageImplUtils.assertNotNull("data must have defined length", data.getLength()); this.data = data; this.length = data.getLength(); this.dataFlux = null; this.dataStream = null; }
StorageImplUtils.assertNotNull("data must have defined length", data.getLength());
public FileParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data must not be null", data); this.data = data; this.length = data.getLength(); this.dataFlux = null; this.dataStream = null; }
class FileParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final BinaryData data; private final Long length; private ParallelTransferOptions parallelTransferOptions; private PathHttpHeaders headers; private Map<String, String> metadata; private String permissions; private String umask; private DataLakeRequestConditions requestConditions; /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataFlux The data to write to the file. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public FileParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; this.data = null; } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param data The {@link BinaryData} to write to the file. */ /** * Constructs a new {@code FileParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public FileParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. */ public FileParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } private FileParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.length = length; this.dataFlux = null; this.data = null; } /** * Gets the data source. * * @return The data to write to the file. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the file. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the data source. * * @return The data to write to the file. */ public BinaryData getData() { return this.data; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated public long getLength() { return length; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public FileParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link PathHttpHeaders}. * * @return {@link PathHttpHeaders} */ public PathHttpHeaders getHeaders() { return headers; } /** * Sets the {@link PathHttpHeaders}. * * @param headers {@link PathHttpHeaders} * @return The updated options */ public FileParallelUploadOptions setHeaders(PathHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the file. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public FileParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the permissions. * * @return the POSIX access permissions for the resource owner, the resource owning group, and others. */ public String getPermissions() { return permissions; } /** * Sets the permissions. * * @param permissions the POSIX access permissions for the resource owner, the resource owning group, and others. * @return The updated options */ public FileParallelUploadOptions setPermissions(String permissions) { this.permissions = permissions; return this; } /** * Gets the umask. * * @return the umask. */ public String getUmask() { return umask; } /** * Sets the umask. * * @param umask Restricts permissions of the resource to be created. * @return The updated options */ public FileParallelUploadOptions setUmask(String umask) { this.umask = umask; return this; } /** * Gets the {@link DataLakeRequestConditions}. * * @return {@link DataLakeRequestConditions} */ public DataLakeRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link DataLakeRequestConditions}. * * @param requestConditions {@link DataLakeRequestConditions} * @return The updated options. */ public FileParallelUploadOptions setRequestConditions(DataLakeRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } }
class FileParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final BinaryData data; private final Long length; private ParallelTransferOptions parallelTransferOptions; private PathHttpHeaders headers; private Map<String, String> metadata; private String permissions; private String umask; private DataLakeRequestConditions requestConditions; /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataFlux The data to write to the file. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public FileParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; this.data = null; } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param data The {@link BinaryData} to write to the file. */ /** * Constructs a new {@code FileParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public FileParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@code FileParallelUploadOptions}. * * @param dataStream The data to write to the blob. The data must be markable. This is in order to support retries. * If the data is not markable, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add * mark support. */ public FileParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } private FileParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.length = length; this.dataFlux = null; this.data = null; } /** * Gets the data source. * * @return The data to write to the file. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the file. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the data source. * * @return The data to write to the file. */ public BinaryData getData() { return this.data; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated public long getLength() { return length; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public FileParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link PathHttpHeaders}. * * @return {@link PathHttpHeaders} */ public PathHttpHeaders getHeaders() { return headers; } /** * Sets the {@link PathHttpHeaders}. * * @param headers {@link PathHttpHeaders} * @return The updated options */ public FileParallelUploadOptions setHeaders(PathHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the file. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public FileParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Gets the permissions. * * @return the POSIX access permissions for the resource owner, the resource owning group, and others. */ public String getPermissions() { return permissions; } /** * Sets the permissions. * * @param permissions the POSIX access permissions for the resource owner, the resource owning group, and others. * @return The updated options */ public FileParallelUploadOptions setPermissions(String permissions) { this.permissions = permissions; return this; } /** * Gets the umask. * * @return the umask. */ public String getUmask() { return umask; } /** * Sets the umask. * * @param umask Restricts permissions of the resource to be created. * @return The updated options */ public FileParallelUploadOptions setUmask(String umask) { this.umask = umask; return this; } /** * Gets the {@link DataLakeRequestConditions}. * * @return {@link DataLakeRequestConditions} */ public DataLakeRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link DataLakeRequestConditions}. * * @param requestConditions {@link DataLakeRequestConditions} * @return The updated options. */ public FileParallelUploadOptions setRequestConditions(DataLakeRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } }
for this link, change to `https://aka.ms/spring/versions instead`.
private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s].%n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] " + "section.%n If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false].", this.acceptedVersions, "https: "https: }
"https:
private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s].%n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] " + "section.%n If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false].", this.acceptedVersions, "https: "https: }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind" + ".Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis" + ".ClientResourcesBuilderCustomizer"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7 = "org.springframework.boot.autoconfigure.amqp" + ".RabbitStreamTemplateConfigurer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6, 2.7]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); supportedVersions.put("2.7", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure version.", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure version."; } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { LOGGER.debug("Current Spring Boot version matching succeeds in Spring Cloud Azure supported " + "versions [{}].", acceptedVersion); return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched.", versionString); return true; } } } return false; } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Currently running on Spring Boot version [{}], trying to match it in Spring Cloud Azure " + "Supported Versions [{}].", version, acceptedVersion); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check current Spring Boot version from Spring Cloud Azure supported versions."); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind" + ".Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis" + ".ClientResourcesBuilderCustomizer"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7 = "org.springframework.boot.autoconfigure.amqp" + ".RabbitStreamTemplateConfigurer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6, 2.7]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); supportedVersions.put("2.7", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure version.", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure version."; } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { LOGGER.debug("The current Spring Boot version matches Spring Cloud Azure accepted version [{}].", acceptedVersion); return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched.", versionString); return true; } } } return false; } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Currently running on Spring Boot version [{}], trying to match it with Spring Cloud Azure " + "accepted version [{}].", version, acceptedVersion); if (!StringUtils.hasText(version)) { throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
This log doesn't make sense. The `version` returns from the `getVersionFromManifest()` method, but the log is `from Spring Cloud Azure supported versions.` What does this mean?
private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Currently running on Spring Boot version [{}], trying to match it in Spring Cloud Azure " + "Supported Versions [{}].", version, acceptedVersion); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check current Spring Boot version from Spring Cloud Azure supported versions."); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } }
LOGGER.info("Cannot check current Spring Boot version from Spring Cloud Azure supported versions.");
private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Currently running on Spring Boot version [{}], trying to match it with Spring Cloud Azure " + "accepted version [{}].", version, acceptedVersion); if (!StringUtils.hasText(version)) { throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind" + ".Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis" + ".ClientResourcesBuilderCustomizer"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7 = "org.springframework.boot.autoconfigure.amqp" + ".RabbitStreamTemplateConfigurer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6, 2.7]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); supportedVersions.put("2.7", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure version.", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure version."; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s].%n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] " + "section.%n If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false].", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { LOGGER.debug("Current Spring Boot version matching succeeds in Spring Cloud Azure supported " + "versions [{}].", acceptedVersion); return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched.", versionString); return true; } } } return false; } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind" + ".Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis" + ".ClientResourcesBuilderCustomizer"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7 = "org.springframework.boot.autoconfigure.amqp" + ".RabbitStreamTemplateConfigurer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6, 2.7]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); supportedVersions.put("2.7", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure version.", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure version."; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s].%n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] " + "section.%n If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false].", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { LOGGER.debug("The current Spring Boot version matches Spring Cloud Azure accepted version [{}].", acceptedVersion); return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched.", versionString); return true; } } } return false; } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
`The current Spring Boot version matches Spring Cloud Azure accepted version [{}]`
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { LOGGER.debug("Current Spring Boot version matching succeeds in Spring Cloud Azure supported " + "versions [{}].", acceptedVersion); return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched.", versionString); return true; } } } return false; }
+ "versions [{}].", acceptedVersion);
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { if (this.matchSpringBootVersionFromManifest(acceptedVersion)) { LOGGER.debug("The current Spring Boot version matches Spring Cloud Azure accepted version [{}].", acceptedVersion); return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQualifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQualifiedClassName)) { LOGGER.debug("Predicate for Spring Boot Version of [{}] was matched.", versionString); return true; } } } return false; }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind" + ".Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis" + ".ClientResourcesBuilderCustomizer"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7 = "org.springframework.boot.autoconfigure.amqp" + ".RabbitStreamTemplateConfigurer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6, 2.7]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); supportedVersions.put("2.7", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure version.", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure version."; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s].%n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] " + "section.%n If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false].", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Currently running on Spring Boot version [{}], trying to match it in Spring Cloud Azure " + "Supported Versions [{}].", version, acceptedVersion); if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check current Spring Boot version from Spring Cloud Azure supported versions."); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind" + ".Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis" + ".ClientResourcesBuilderCustomizer"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7 = "org.springframework.boot.autoconfigure.amqp" + ".RabbitStreamTemplateConfigurer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6, 2.7]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); supportedVersions.put("2.7", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_7); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure version.", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure version."; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s.%n" + "You can find the latest Spring Boot versions here [%s].%n" + "If you want to learn more about the Spring Cloud Azure compatibility, " + "you can visit this page [%s] and check the [Which Version of Spring Cloud Azure Should I Use] " + "section.%n If you want to disable this check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false].", this.acceptedVersions, "https: "https: } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); LOGGER.debug("Currently running on Spring Boot version [{}], trying to match it with Spring Cloud Azure " + "accepted version [{}].", version, acceptedVersion); if (!StringUtils.hasText(version)) { throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }