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
GraalVM can mean 3 different things in the Java world: 1) GraalVM native 2) GraalVM JVM only written in Java 3) GraalVM Truffle (https://www.graalvm.org/latest/reference-manual/java-on-truffle/) Generally, when we talk about GraalVM in Java, it often means GraalVM native but it may also mean the two others. So, I would prefer `native` to avoid any ambiguity.
private static String getJavaRuntime() { if(isGraalVmNative()) { return "!native"; } return ""; }
return "!native";
private static String getJavaRuntime() { if(isGraalVmNative()) { return "!native"; } return ""; }
class VersionGenerator { private static final String UNKNOWN_VERSION_VALUE = "unknown"; private static final String artifactName; private static final String artifactVersion; private static final String sdkVersionString; static { Map<String, String> properties = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); artifactName = properties.get("name"); artifactVersion = properties.get("version"); sdkVersionString = "java" + getJavaVersion() + getJavaRuntime() + ":" + "otel" + getOpenTelemetryApiVersion() + ":" + "ext" + artifactVersion; } /** * This method returns artifact name. * * @return artifactName. */ public static String getArtifactName() { return artifactName; } /** * This method returns artifact version. * * @return artifactVersion. */ public static String getArtifactVersion() { return artifactVersion; } /** * This method returns sdk version string as per the below format javaX:otelY:extZ X = Java * version, Y = opentelemetry version, Z = exporter version * * @return sdkVersionString. */ public static String getSdkVersion() { return sdkVersionString; } private static String getJavaVersion() { return System.getProperty("java.version"); } private static boolean isGraalVmNative() { String imageCode = System.getProperty("org.graalvm.nativeimage.imagecode"); return imageCode != null; } private static String getOpenTelemetryApiVersion() { Map<String, String> properties = CoreUtils.getProperties("io/opentelemetry/api/version.properties"); if (properties == null) { return UNKNOWN_VERSION_VALUE; } String version = properties.get("sdk.version"); return version != null ? version : UNKNOWN_VERSION_VALUE; } private VersionGenerator() { } }
class VersionGenerator { private static final String UNKNOWN_VERSION_VALUE = "unknown"; private static final String artifactName; private static final String artifactVersion; private static final String sdkVersionString; static { Map<String, String> properties = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); artifactName = properties.get("name"); artifactVersion = properties.get("version"); sdkVersionString = "java" + getJavaVersion() + getJavaRuntime() + ":" + "otel" + getOpenTelemetryApiVersion() + ":" + "ext" + artifactVersion; } /** * This method returns artifact name. * * @return artifactName. */ public static String getArtifactName() { return artifactName; } /** * This method returns artifact version. * * @return artifactVersion. */ public static String getArtifactVersion() { return artifactVersion; } /** * This method returns sdk version string as per the below format javaX:otelY:extZ X = Java * version, Y = opentelemetry version, Z = exporter version * * @return sdkVersionString. */ public static String getSdkVersion() { return sdkVersionString; } private static String getJavaVersion() { return System.getProperty("java.version"); } private static boolean isGraalVmNative() { String imageCode = System.getProperty("org.graalvm.nativeimage.imagecode"); return imageCode != null; } private static String getOpenTelemetryApiVersion() { Map<String, String> properties = CoreUtils.getProperties("io/opentelemetry/api/version.properties"); if (properties == null) { return UNKNOWN_VERSION_VALUE; } String version = properties.get("sdk.version"); return version != null ? version : UNKNOWN_VERSION_VALUE; } private VersionGenerator() { } }
makes sense 👍
private static String getJavaRuntime() { if(isGraalVmNative()) { return "!native"; } return ""; }
return "!native";
private static String getJavaRuntime() { if(isGraalVmNative()) { return "!native"; } return ""; }
class VersionGenerator { private static final String UNKNOWN_VERSION_VALUE = "unknown"; private static final String artifactName; private static final String artifactVersion; private static final String sdkVersionString; static { Map<String, String> properties = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); artifactName = properties.get("name"); artifactVersion = properties.get("version"); sdkVersionString = "java" + getJavaVersion() + getJavaRuntime() + ":" + "otel" + getOpenTelemetryApiVersion() + ":" + "ext" + artifactVersion; } /** * This method returns artifact name. * * @return artifactName. */ public static String getArtifactName() { return artifactName; } /** * This method returns artifact version. * * @return artifactVersion. */ public static String getArtifactVersion() { return artifactVersion; } /** * This method returns sdk version string as per the below format javaX:otelY:extZ X = Java * version, Y = opentelemetry version, Z = exporter version * * @return sdkVersionString. */ public static String getSdkVersion() { return sdkVersionString; } private static String getJavaVersion() { return System.getProperty("java.version"); } private static boolean isGraalVmNative() { String imageCode = System.getProperty("org.graalvm.nativeimage.imagecode"); return imageCode != null; } private static String getOpenTelemetryApiVersion() { Map<String, String> properties = CoreUtils.getProperties("io/opentelemetry/api/version.properties"); if (properties == null) { return UNKNOWN_VERSION_VALUE; } String version = properties.get("sdk.version"); return version != null ? version : UNKNOWN_VERSION_VALUE; } private VersionGenerator() { } }
class VersionGenerator { private static final String UNKNOWN_VERSION_VALUE = "unknown"; private static final String artifactName; private static final String artifactVersion; private static final String sdkVersionString; static { Map<String, String> properties = CoreUtils.getProperties("azure-monitor-opentelemetry-exporter.properties"); artifactName = properties.get("name"); artifactVersion = properties.get("version"); sdkVersionString = "java" + getJavaVersion() + getJavaRuntime() + ":" + "otel" + getOpenTelemetryApiVersion() + ":" + "ext" + artifactVersion; } /** * This method returns artifact name. * * @return artifactName. */ public static String getArtifactName() { return artifactName; } /** * This method returns artifact version. * * @return artifactVersion. */ public static String getArtifactVersion() { return artifactVersion; } /** * This method returns sdk version string as per the below format javaX:otelY:extZ X = Java * version, Y = opentelemetry version, Z = exporter version * * @return sdkVersionString. */ public static String getSdkVersion() { return sdkVersionString; } private static String getJavaVersion() { return System.getProperty("java.version"); } private static boolean isGraalVmNative() { String imageCode = System.getProperty("org.graalvm.nativeimage.imagecode"); return imageCode != null; } private static String getOpenTelemetryApiVersion() { Map<String, String> properties = CoreUtils.getProperties("io/opentelemetry/api/version.properties"); if (properties == null) { return UNKNOWN_VERSION_VALUE; } String version = properties.get("sdk.version"); return version != null ? version : UNKNOWN_VERSION_VALUE; } private VersionGenerator() { } }
In V2 we moved towards dedicated backing methods to support each public receiveMessages variant (sync, async, session-sync, session-async, processor, session-processor) rather than one catch-all backing method like in V1. So this `nonSessionSyncReceiveV2()` is the backing method for non-session sync receiver. Unlike V1 there is no need to wrap the messages Flux into FluxAutoLockRenew operator type, a similar lock renew provided by that operator is available in V2 `beginLockRenew` method. The `beginLockRenew` is the one used for V2 Processor and it can be used for lock renewal for V2 sync receive as well.
Flux<ServiceBusReceivedMessage> nonSessionSyncReceiveV2() { assert isOnV2 && !isSessionEnabled; final Flux<ServiceBusReceivedMessage> messages = getOrCreateConsumer().receive(); return receiverOptions.isAutoLockRenewEnabled() ? messages.doOnNext(this::beginLockRenewal) : messages; }
return receiverOptions.isAutoLockRenewEnabled() ? messages.doOnNext(this::beginLockRenewal) : messages;
Flux<ServiceBusReceivedMessage> nonSessionSyncReceiveV2() { assert isOnV2 && !isSessionEnabled; final Flux<ServiceBusReceivedMessage> messages = getOrCreateConsumer().receive(); return receiverOptions.isAutoLockRenewEnabled() ? messages.doOnNext(this::beginLockRenewal) : messages; }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final Duration EXPIRED_RENEWAL_CLEANUP_INTERVAL = Duration.ofMinutes(2); private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ConnectionCacheWrapper connectionCacheWrapper; private final boolean isOnV2; private final Mono<ServiceBusAmqpConnection> connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final IServiceBusSessionManager sessionManager; private final boolean isSessionEnabled; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionCacheWrapper The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ConnectionCacheWrapper connectionCacheWrapper, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionCacheWrapper = Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null."); this.connectionProcessor = this.connectionCacheWrapper.getConnection(); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = null; if (receiverOptions.getSessionId() != null || receiverOptions.getMaxConcurrentSessions() != null) { throw new IllegalStateException("Session-specific options are not expected to be present on a client for session unaware entity."); } this.isSessionEnabled = false; this.isOnV2 = this.connectionCacheWrapper.isV2(); this.managementNodeLocks = new LockContainer<OffsetDateTime>(cleanupInterval); final Consumer<LockRenewalOperation> onExpired = renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }; this.renewalContainer = new LockContainer<LockRenewalOperation>(EXPIRED_RENEWAL_CLEANUP_INTERVAL, onExpired); this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ConnectionCacheWrapper connectionCacheWrapper, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, IServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionCacheWrapper = Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null."); this.connectionProcessor = this.connectionCacheWrapper.getConnection(); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.isSessionEnabled = true; this.isOnV2 = this.connectionCacheWrapper.isV2(); final boolean isV2SessionManager = this.sessionManager instanceof ServiceBusSingleSessionManager; if (isOnV2 ^ isV2SessionManager) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("For V2 Session, the manager should be ServiceBusSingleSessionManager, and ConnectionCache should be on V2.")); } this.managementNodeLocks = new LockContainer<OffsetDateTime>(cleanupInterval); final Consumer<LockRenewalOperation> onExpired = renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }; this.renewalContainer = new LockContainer<LockRenewalOperation>(EXPIRED_RENEWAL_CLEANUP_INTERVAL, onExpired); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); return node .peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages) .doOnNext(next -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, next.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Last peeked sequence number in batch."); }); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition to * a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable error * or exhausts the retries, the Subscriber's {@link org.reactivestreams.Subscriber * will be notified with this error. No further messages will be delivered to {@link org.reactivestreams.Subscriber * after the terminal event; the application must create a new client to resume the receive. Re-subscribing to the Flux * of the old client will have no effect. * </p> * <p> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } if (isOnV2) { if (isSessionEnabled) { return sessionReactiveReceiveV2(); } else { return nonSessionReactiveReceiveV2(); } } return receiveMessagesNoBackPressure().limitRate(1, 0); } @SuppressWarnings("try") Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } private Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!isSessionEnabled && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock, tracer); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } return tracer.traceRenewMessageLock(renewMessageLock(message.getLockToken()), message) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> isOnV2 ? offsetDateTime : managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation() .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = asyncReceiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * & * Disposable disposable = transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * asyncReceiver.receiveDeferredMessage& * asyncReceiver.complete& * asyncReceiver.abandon& * * & * return operations.then& * & * & * System.err.println& * & * System.out.println& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(AmqpSession::createTransaction) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = asyncReceiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * & * Disposable disposable = transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * asyncReceiver.receiveDeferredMessage& * asyncReceiver.complete& * asyncReceiver.abandon& * * & * return operations.then& * & * & * System.err.println& * & * System.out.println& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = asyncReceiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * & * Disposable disposable = transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * asyncReceiver.receiveDeferredMessage& * asyncReceiver.complete& * asyncReceiver.abandon& * * & * return operations.then& * & * & * System.err.println& * & * System.out.println& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); } /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition started."); final Mono<Void> updateDispositionOperation; if (isSessionEnabled) { if (isOnV2) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .<Void>then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition completed."); message.setIsSettled(); })).onErrorResume(DeliveryNotOnLinkException.class, __ -> { LOGGER.info("Could not perform disposition on session manger. Performing on management node."); return dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); }); } else { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); }); } } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); } else { if (isOnV2) { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .<Void>then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })).onErrorResume(DeliveryNotOnLinkException.class, __ -> { return dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); }); } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private Mono<Void> dispositionViaManagementNode(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition (via management node) completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); } private ServiceBusAsyncConsumer getOrCreateConsumer() { if (isSessionEnabled) { throw LOGGER.logExceptionAsError(new IllegalStateException("The ServiceBusAsyncConsumer is expected to work only with session unaware entity.")); } final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", false) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionCacheWrapper.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono .repeat() .filter(link -> !link.isDisposed()); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionCacheWrapper.getRetryOptions()); final ServiceBusAsyncConsumer newConsumer; if (isOnV2) { final MessageFlux messageFlux = new MessageFlux(receiveLinkFlux, receiverOptions.getPrefetchCount(), CreditFlowMode.RequestDriven, retryPolicy); newConsumer = new ServiceBusAsyncConsumer(linkName, messageFlux, messageSerializer, receiverOptions, instrumentation); } else { final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); } if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (!CoreUtils.isNullOrEmpty(sessionId)) { return isSessionEnabled ? sessionManager.getLinkName(sessionId) : null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } private Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager.getLinkName(sessionId); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> tracer.traceMono("ServiceBus.renewSessionLock", channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } private Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation(); } private Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } private Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionCacheWrapper.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } boolean isSessionEnabled() { return isSessionEnabled; } boolean isAutoLockRenewRequested() { return receiverOptions.isAutoLockRenewEnabled(); } boolean isV2() { return isOnV2; } Flux<ServiceBusReceivedMessage> nonSessionProcessorReceiveV2() { assert isOnV2 && !isSessionEnabled; return getOrCreateConsumer().receive(); } private Flux<ServiceBusReceivedMessage> nonSessionReactiveReceiveV2() { assert isOnV2 && !isSessionEnabled; final boolean enableAutoDisposition = receiverOptions.isEnableAutoComplete(); final boolean enableAutoLockRenew = receiverOptions.isAutoLockRenewEnabled(); final Flux<ServiceBusReceivedMessage> messages = getOrCreateConsumer().receive() .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); if (enableAutoDisposition | enableAutoLockRenew) { return new AutoDispositionLockRenew(messages, this, enableAutoDisposition, enableAutoLockRenew, completionLock); } else { return messages; } } private Flux<ServiceBusReceivedMessage> sessionReactiveReceiveV2() { assert isOnV2 && isSessionEnabled && sessionManager instanceof ServiceBusSingleSessionManager; final ServiceBusSingleSessionManager singleSessionManager = (ServiceBusSingleSessionManager) sessionManager; final Flux<ServiceBusReceivedMessage> messages = singleSessionManager.receiveMessages(); final boolean enableAutoDisposition = receiverOptions.isEnableAutoComplete(); if (enableAutoDisposition) { return new AutoDispositionLockRenew(messages, this, true, false, completionLock); } else { return messages; } } Flux<ServiceBusReceivedMessage> sessionSyncReceiveV2() { assert isOnV2 && isSessionEnabled && sessionManager instanceof ServiceBusSingleSessionManager; final ServiceBusSingleSessionManager singleSessionManager = (ServiceBusSingleSessionManager) sessionManager; return singleSessionManager.receiveMessages(); } /** * Begin the recurring lock renewal of the given message. * * @param message the message to keep renewing. * @return {@link Disposable} that when disposed of, results in stopping the recurring renewal. */ Disposable beginLockRenewal(ServiceBusReceivedMessage message) { if (isSessionEnabled) { throw LOGGER.logExceptionAsError(new IllegalStateException("Renewing message lock is an invalid operation when working with sessions.")); } final Duration maxRenewalDuration = receiverOptions.getMaxLockRenewDuration(); Objects.requireNonNull(maxRenewalDuration, "'receivingOptions.maxAutoLockRenewDuration' is required for recurring lock renewal."); if (message == null) { return Disposables.disposed(); } final String lockToken = message.getLockToken(); if (Objects.isNull(lockToken)) { LOGGER.atWarning() .addKeyValue(SEQUENCE_NUMBER_KEY, message.getSequenceNumber()) .log("Unexpected, LockToken is required for recurring lock renewal."); return Disposables.disposed(); } final OffsetDateTime initialExpireAt = message.getLockedUntil(); if (Objects.isNull(initialExpireAt)) { LOGGER.atWarning() .addKeyValue(SEQUENCE_NUMBER_KEY, message.getSequenceNumber()) .log("Unexpected, LockedUntil is required for recurring lock renewal."); return Disposables.disposed(); } final Mono<OffsetDateTime> renewalMono = tracer.traceRenewMessageLock(this.renewMessageLock(lockToken) .map(nextExpireAt -> { message.setLockedUntil(nextExpireAt); return nextExpireAt; }), message); final LockRenewalOperation recurringRenewal = new LockRenewalOperation(lockToken, maxRenewalDuration, false, __ -> renewalMono, initialExpireAt); try { renewalContainer.addOrUpdate(lockToken, OffsetDateTime.now().plus(maxRenewalDuration), recurringRenewal); } catch (Exception e) { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .log("Exception occurred while updating lockContainer.", e); } return Disposables.composite(() -> recurringRenewal.close(), () -> renewalContainer.remove(lockToken)); } }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final Duration EXPIRED_RENEWAL_CLEANUP_INTERVAL = Duration.ofMinutes(2); private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ConnectionCacheWrapper connectionCacheWrapper; private final boolean isOnV2; private final Mono<ServiceBusAmqpConnection> connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final IServiceBusSessionManager sessionManager; private final boolean isSessionEnabled; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionCacheWrapper The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ConnectionCacheWrapper connectionCacheWrapper, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionCacheWrapper = Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null."); this.connectionProcessor = this.connectionCacheWrapper.getConnection(); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = null; if (receiverOptions.getSessionId() != null || receiverOptions.getMaxConcurrentSessions() != null) { throw new IllegalStateException("Session-specific options are not expected to be present on a client for session unaware entity."); } this.isSessionEnabled = false; this.isOnV2 = this.connectionCacheWrapper.isV2(); this.managementNodeLocks = new LockContainer<OffsetDateTime>(cleanupInterval); final Consumer<LockRenewalOperation> onExpired = renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }; this.renewalContainer = new LockContainer<LockRenewalOperation>(EXPIRED_RENEWAL_CLEANUP_INTERVAL, onExpired); this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ConnectionCacheWrapper connectionCacheWrapper, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, IServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionCacheWrapper = Objects.requireNonNull(connectionCacheWrapper, "'connectionCacheWrapper' cannot be null."); this.connectionProcessor = this.connectionCacheWrapper.getConnection(); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.isSessionEnabled = true; this.isOnV2 = this.connectionCacheWrapper.isV2(); final boolean isV2SessionManager = this.sessionManager instanceof ServiceBusSingleSessionManager; if (isOnV2 ^ isV2SessionManager) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("For V2 Session, the manager should be ServiceBusSingleSessionManager, and ConnectionCache should be on V2.")); } this.managementNodeLocks = new LockContainer<OffsetDateTime>(cleanupInterval); final Consumer<LockRenewalOperation> onExpired = renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }; this.renewalContainer = new LockContainer<LockRenewalOperation>(EXPIRED_RENEWAL_CLEANUP_INTERVAL, onExpired); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); return node .peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages) .doOnNext(next -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, next.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Last peeked sequence number in batch."); }); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * <p> * The client uses an AMQP link underneath to receive the messages; the client will transparently transition to * a new AMQP link if the current one encounters a retriable error. When the client experiences a non-retriable error * or exhausts the retries, the Subscriber's {@link org.reactivestreams.Subscriber * will be notified with this error. No further messages will be delivered to {@link org.reactivestreams.Subscriber * after the terminal event; the application must create a new client to resume the receive. Re-subscribing to the Flux * of the old client will have no effect. * </p> * <p> * Note: A few examples of non-retriable errors are - the application attempting to connect to a queue that does not * exist, deleting or disabling the queue in the middle of receiving, the user explicitly initiating Geo-DR. * These are certain events where the Service Bus communicates to the client that a non-retriable error occurred. * </p> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } if (isOnV2) { if (isSessionEnabled) { return sessionReactiveReceiveV2(); } else { return nonSessionReactiveReceiveV2(); } } return receiveMessagesNoBackPressure().limitRate(1, 0); } @SuppressWarnings("try") Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } private Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!isSessionEnabled && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock, tracer); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } return tracer.traceRenewMessageLock(renewMessageLock(message.getLockToken()), message) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> isOnV2 ? offsetDateTime : managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (isSessionEnabled) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation() .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = asyncReceiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * & * Disposable disposable = transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * asyncReceiver.receiveDeferredMessage& * asyncReceiver.complete& * asyncReceiver.abandon& * * & * return operations.then& * & * & * System.err.println& * & * System.out.println& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(AmqpSession::createTransaction) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = asyncReceiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * & * Disposable disposable = transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * asyncReceiver.receiveDeferredMessage& * asyncReceiver.complete& * asyncReceiver.abandon& * * & * return operations.then& * & * & * System.err.println& * & * System.out.println& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = asyncReceiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * & * Disposable disposable = transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * asyncReceiver.receiveDeferredMessage& * asyncReceiver.complete& * asyncReceiver.abandon& * * & * return operations.then& * & * & * System.err.println& * & * System.out.println& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); } /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition started."); final Mono<Void> updateDispositionOperation; if (isSessionEnabled) { if (isOnV2) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .<Void>then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition completed."); message.setIsSettled(); })).onErrorResume(DeliveryNotOnLinkException.class, __ -> { LOGGER.info("Could not perform disposition on session manger. Performing on management node."); return dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); }); } else { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); }); } } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); } else { if (isOnV2) { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .<Void>then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })).onErrorResume(DeliveryNotOnLinkException.class, __ -> { return dispositionViaManagementNode(message, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext); }); } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private Mono<Void> dispositionViaManagementNode(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Disposition (via management node) completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); } private ServiceBusAsyncConsumer getOrCreateConsumer() { if (isSessionEnabled) { throw LOGGER.logExceptionAsError(new IllegalStateException("The ServiceBusAsyncConsumer is expected to work only with session unaware entity.")); } final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", false) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionCacheWrapper.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono .repeat() .filter(link -> !link.isDisposed()); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionCacheWrapper.getRetryOptions()); final ServiceBusAsyncConsumer newConsumer; if (isOnV2) { final MessageFlux messageFlux = new MessageFlux(receiveLinkFlux, receiverOptions.getPrefetchCount(), CreditFlowMode.RequestDriven, retryPolicy); newConsumer = new ServiceBusAsyncConsumer(linkName, messageFlux, messageSerializer, receiverOptions, instrumentation); } else { final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); } if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (!CoreUtils.isNullOrEmpty(sessionId)) { return isSessionEnabled ? sessionManager.getLinkName(sessionId) : null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } private Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager.getLinkName(sessionId); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> tracer.traceMono("ServiceBus.renewSessionLock", channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } private Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation(); } private Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } private Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!isSessionEnabled) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } assert sessionManager != null; final String linkName = sessionManager.getLinkName(sessionId); return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionCacheWrapper.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } boolean isSessionEnabled() { return isSessionEnabled; } boolean isAutoLockRenewRequested() { return receiverOptions.isAutoLockRenewEnabled(); } boolean isV2() { return isOnV2; } Flux<ServiceBusReceivedMessage> nonSessionProcessorReceiveV2() { assert isOnV2 && !isSessionEnabled; return getOrCreateConsumer().receive(); } private Flux<ServiceBusReceivedMessage> nonSessionReactiveReceiveV2() { assert isOnV2 && !isSessionEnabled; final boolean enableAutoDisposition = receiverOptions.isEnableAutoComplete(); final boolean enableAutoLockRenew = receiverOptions.isAutoLockRenewEnabled(); final Flux<ServiceBusReceivedMessage> messages = getOrCreateConsumer().receive() .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); if (enableAutoDisposition | enableAutoLockRenew) { return new AutoDispositionLockRenew(messages, this, enableAutoDisposition, enableAutoLockRenew, completionLock); } else { return messages; } } private Flux<ServiceBusReceivedMessage> sessionReactiveReceiveV2() { assert isOnV2 && isSessionEnabled && sessionManager instanceof ServiceBusSingleSessionManager; final ServiceBusSingleSessionManager singleSessionManager = (ServiceBusSingleSessionManager) sessionManager; final Flux<ServiceBusReceivedMessage> messages = singleSessionManager.receiveMessages(); final boolean enableAutoDisposition = receiverOptions.isEnableAutoComplete(); if (enableAutoDisposition) { return new AutoDispositionLockRenew(messages, this, true, false, completionLock); } else { return messages; } } Flux<ServiceBusReceivedMessage> sessionSyncReceiveV2() { assert isOnV2 && isSessionEnabled && sessionManager instanceof ServiceBusSingleSessionManager; final ServiceBusSingleSessionManager singleSessionManager = (ServiceBusSingleSessionManager) sessionManager; return singleSessionManager.receiveMessages(); } /** * Begin the recurring lock renewal of the given message. * * @param message the message to keep renewing. * @return {@link Disposable} that when disposed of, results in stopping the recurring renewal. */ Disposable beginLockRenewal(ServiceBusReceivedMessage message) { if (isSessionEnabled) { throw LOGGER.logExceptionAsError(new IllegalStateException("Renewing message lock is an invalid operation when working with sessions.")); } final Duration maxRenewalDuration = receiverOptions.getMaxLockRenewDuration(); Objects.requireNonNull(maxRenewalDuration, "'receivingOptions.maxAutoLockRenewDuration' is required for recurring lock renewal."); if (message == null) { return Disposables.disposed(); } final String lockToken = message.getLockToken(); if (Objects.isNull(lockToken)) { LOGGER.atWarning() .addKeyValue(SEQUENCE_NUMBER_KEY, message.getSequenceNumber()) .log("Unexpected, LockToken is required for recurring lock renewal."); return Disposables.disposed(); } final OffsetDateTime initialExpireAt = message.getLockedUntil(); if (Objects.isNull(initialExpireAt)) { LOGGER.atWarning() .addKeyValue(SEQUENCE_NUMBER_KEY, message.getSequenceNumber()) .log("Unexpected, LockedUntil is required for recurring lock renewal."); return Disposables.disposed(); } final Mono<OffsetDateTime> renewalMono = tracer.traceRenewMessageLock(this.renewMessageLock(lockToken) .map(nextExpireAt -> { message.setLockedUntil(nextExpireAt); return nextExpireAt; }), message); final LockRenewalOperation recurringRenewal = new LockRenewalOperation(lockToken, maxRenewalDuration, false, __ -> renewalMono, initialExpireAt); try { renewalContainer.addOrUpdate(lockToken, OffsetDateTime.now().plus(maxRenewalDuration), recurringRenewal); } catch (Exception e) { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .log("Exception occurred while updating lockContainer.", e); } return Disposables.composite(() -> recurringRenewal.close(), () -> renewalContainer.remove(lockToken)); } }
keep the update test, just change it to update the storage account to disallow. And verify it.
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
.disallowCrossTenantReplication()
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .disallowCrossTenantReplication() .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
The `allowCrossTenantReplication` interface has been added in `Create` mode, and this interface has been called in the test case [`canDisallowCrossTenantReplicationOnStorageAccount`](https://github.com/v-hongli1/azure-sdk-for-java/blob/issue%235259_BreakingChange/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java#L222), so ``` storageAccount.update() .allowCrossTenantReplication() .apply(); ``` can be removed. However, verification of the initial value of `cross-tenant replication` is still necessary such as test case [`canAllowCrossTenantReplicationOnStorageAccount`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java#L204).
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
.disallowCrossTenantReplication()
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .disallowCrossTenantReplication() .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
Just add a ```java storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); ```
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
.disallowCrossTenantReplication()
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .disallowCrossTenantReplication() .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
Removed the invoke of interface `disallowCrossTenantReplication` from the test case `canAllowCrossTenantReplicationOnStorageAccount`.
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
.disallowCrossTenantReplication()
public void canDisallowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .allowCrossTenantReplication() .create(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .disallowCrossTenantReplication() .apply(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .disallowCrossTenantReplication() .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
class StorageAccountOperationsTests extends StorageManagementTest { private String rgName = ""; private String saName = ""; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); saName = generateRandomResourceName("javacsmsa", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCRUDStorageAccount() throws Exception { Mono<StorageAccount> resourceStream = storageManager .storageAccounts() .define(saName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withGeneralPurposeAccountKindV2() .withTag("tag1", "value1") .withHnsEnabled(true) .withAzureFilesAadIntegrationEnabled(false) .withInfrastructureEncryption() .createAsync(); StorageAccount storageAccount = resourceStream.block(); Assertions.assertEquals(rgName, storageAccount.resourceGroupName()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccount.skuType().name()); Assertions.assertTrue(storageAccount.isHnsEnabled()); Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); PagedIterable<StorageAccount> accounts = storageManager.storageAccounts().listByResourceGroup(rgName); boolean found = false; for (StorageAccount account : accounts) { if (account.name().equals(saName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, storageAccount.tags().size()); storageAccount = storageManager.storageAccounts().getByResourceGroup(rgName, saName); Assertions.assertNotNull(storageAccount); List<StorageAccountKey> keys = storageAccount.getKeys(); Assertions.assertTrue(keys.size() > 0); StorageAccountKey oldKey = keys.get(0); List<StorageAccountKey> updatedKeys = storageAccount.regenerateKey(oldKey.keyName()); Assertions.assertTrue(updatedKeys.size() > 0); for (StorageAccountKey updatedKey : updatedKeys) { if (updatedKey.keyName().equalsIgnoreCase(oldKey.keyName())) { if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKey.value(), updatedKey.value()); } break; } } Assertions.assertTrue(storageAccount.infrastructureEncryptionEnabled()); Map<StorageService, StorageAccountEncryptionStatus> statuses = storageAccount.encryptionStatuses(); Assertions.assertNotNull(statuses); Assertions.assertTrue(statuses.size() > 0); Assertions.assertTrue(statuses.containsKey(StorageService.BLOB)); StorageAccountEncryptionStatus blobServiceEncryptionStatus = statuses.get(StorageService.BLOB); Assertions.assertNotNull(blobServiceEncryptionStatus); Assertions.assertTrue(blobServiceEncryptionStatus.isEnabled()); Assertions.assertTrue(statuses.containsKey(StorageService.FILE)); StorageAccountEncryptionStatus fileServiceEncryptionStatus = statuses.get(StorageService.FILE); Assertions.assertNotNull(fileServiceEncryptionStatus); Assertions.assertTrue(fileServiceEncryptionStatus.isEnabled()); storageAccount = storageAccount.update() .withSku(StorageAccountSkuType.STANDARD_LRS).withTag("tag2", "value2").apply(); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertEquals(2, storageAccount.tags().size()); } @Test public void canEnableLargeFileSharesOnStorageAccount() throws Exception { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withLargeFileShares(true) .create(); Assertions.assertTrue(storageAccount.isLargeFileSharesEnabled()); } @Test public void storageAccountDefault() { String saName2 = generateRandomResourceName("javacsmsa", 15); StorageAccount storageAccountDefault = storageManager.storageAccounts().define(saName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); Assertions.assertEquals(Kind.STORAGE_V2, storageAccountDefault.kind()); Assertions.assertEquals(SkuName.STANDARD_RAGRS, storageAccountDefault.skuType().name()); Assertions.assertTrue(storageAccountDefault.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccountDefault.minimumTlsVersion()); Assertions.assertTrue(storageAccountDefault.isBlobPublicAccessAllowed()); Assertions.assertTrue(storageAccountDefault.isSharedKeyAccessAllowed()); StorageAccount storageAccount = storageAccountDefault.update() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .apply(); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); storageAccount = storageManager.storageAccounts().define(saName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .withGeneralPurposeAccountKind() .withHttpAndHttpsTraffic() .withMinimumTlsVersion(MinimumTlsVersion.TLS1_1) .disableBlobPublicAccess() .disableSharedKeyAccess() .create(); Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } @Test public void canAllowCrossTenantReplicationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isAllowCrossTenantReplication()); storageAccount.update() .allowCrossTenantReplication() .apply(); Assertions.assertTrue(storageAccount.isAllowCrossTenantReplication()); } @Test @Test public void canEnableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .create(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .enableDefaultToOAuthAuthentication() .apply(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void canDisableDefaultToOAuthAuthenticationOnStorageAccount() { StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.STANDARD_LRS) .enableDefaultToOAuthAuthentication() .create(); Assertions.assertTrue(storageAccount.isDefaultToOAuthAuthentication()); storageAccount.update() .disableDefaultToOAuthAuthentication() .apply(); Assertions.assertFalse(storageAccount.isDefaultToOAuthAuthentication()); } @Test public void createStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewUserAssignedManagedServiceIdentity(identityCreatable) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithNewUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); Creatable<com.azure.resourcemanager.msi.models.Identity> identityCreatable = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withNewUserAssignedManagedServiceIdentity(identityCreatable).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void createStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithExistUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); Assertions.assertNull(storageAccount.innerModel().identity()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateStorageAccountWithoutUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemUserAssignedToNone() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withoutSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()).apply(); Assertions.assertEquals(IdentityType.NONE, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withoutSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withoutUserAssignedManagedServiceIdentity(defaultIdentity.id()) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromUserAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .create(); Assertions.assertEquals(IdentityType.USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromSystemAssignedToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertTrue(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); storageAccount.update().withExistingUserAssignedManagedServiceIdentity(defaultIdentity).apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void updateIdentityFromNoneToSystemUserAssigned() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); com.azure.resourcemanager.msi.models.Identity defaultIdentity = msiManager .identities() .define(generateRandomResourceName("javacsmmsi", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); storageAccount.update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(defaultIdentity) .apply(); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, storageAccount.innerModel().identity().type()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(storageAccount.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertFalse(storageAccount.userAssignedManagedServiceIdentityIds().isEmpty()); } @Test public void canCreateStorageAccountWithDisabledPublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); } @Test public void canUpdatePublicNetworkAccess() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); StorageAccount storageAccount = storageManager .storageAccounts() .define(saName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withSystemAssignedManagedServiceIdentity() .create(); storageAccount.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, storageAccount.publicNetworkAccess()); storageAccount.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, storageAccount.publicNetworkAccess()); } }
please add a comment for this non-playback block, e.g. "principalId redacted"
public void canCreateVirtualMachineScaleSetWithLMSIAndEMSI() throws Exception { String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); Network vmssNetwork = this .networkManager .networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); VirtualMachineScaleSet virtualMachineScaleSet = this .computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withSku(virtualMachineScaleSetSkuTypes) .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") .withoutPrimaryInternetFacingLoadBalancer() .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment; if (!isPlaybackMode()) { assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); } PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this .msiManager .authorizationManager() .roleAssignments() .listByScope( resourceManager.resourceGroups().getByName(virtualMachineScaleSet.resourceGroupName()).id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); if (!isPlaybackMode()) { assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); } }
if (!isPlaybackMode()) {
public void canCreateVirtualMachineScaleSetWithLMSIAndEMSI() throws Exception { String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); Network vmssNetwork = this .networkManager .networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); VirtualMachineScaleSet virtualMachineScaleSet = this .computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") .withoutPrimaryInternetFacingLoadBalancer() .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); if (!isPlaybackMode()) { PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this .msiManager .authorizationManager() .roleAssignments() .listByScope( resourceManager.resourceGroups().getByName(virtualMachineScaleSet.resourceGroupName()).id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); } }
class VirtualMachineScaleSetEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST2; private final String vmssName = "javavmss"; private ResourceGroup resourceGroup; VirtualMachineScaleSetSkuTypes virtualMachineScaleSetSkuTypes = VirtualMachineScaleSetSkuTypes.fromSkuNameAndTier("Standard_D2s_v3", "Standard"); @BeforeEach public void initResources() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); } @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); Network vmssNetwork = this .networkManager .networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); VirtualMachineScaleSet virtualMachineScaleSet = this .computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withSku(virtualMachineScaleSetSkuTypes) .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") .withoutPrimaryInternetFacingLoadBalancer() .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); Assertions .assertNull( virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions .assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment; if (!isPlaybackMode()) { assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); } PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); if (!isPlaybackMode()) { assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); } emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachineScaleSet .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); if (virtualMachineScaleSet.managedServiceIdentityType() != null) { Assertions .assertTrue(virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachineScaleSet.refresh(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); if (virtualMachineScaleSet.managedServiceIdentityType() != null) { Assertions .assertTrue(virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachineScaleSet .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet .managedServiceIdentityType() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); virtualMachineScaleSet.refresh(); Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet .managedServiceIdentityType() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachineScaleSet.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet .managedServiceIdentityType() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); virtualMachineScaleSet.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); virtualMachineScaleSet.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); if (virtualMachineScaleSet.managedServiceIdentityType() != null) { Assertions .assertTrue(virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); } @Test @Test public void canUpdateVirtualMachineScaleSetWithEMSIAndLMSI() throws Exception { String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); Network vmssNetwork = this .networkManager .networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); VirtualMachineScaleSet virtualMachineScaleSet = this .computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withSku(virtualMachineScaleSetSkuTypes) .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") .withoutPrimaryInternetFacingLoadBalancer() .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachineScaleSet = virtualMachineScaleSet.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachineScaleSet.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachineScaleSet = virtualMachineScaleSet .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachineScaleSet.innerModel().identity().userAssignedIdentities().keySet(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachineScaleSet.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
class VirtualMachineScaleSetEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST2; private final String vmssName = "javavmss"; private ResourceGroup resourceGroup; @BeforeEach public void initResources() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create(); } @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCreateUpdateVirtualMachineScaleSetWithEMSI() throws Exception { String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); Network vmssNetwork = this .networkManager .networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); VirtualMachineScaleSet virtualMachineScaleSet = this .computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") .withoutPrimaryInternetFacingLoadBalancer() .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .create(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); Assertions .assertNull( virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions .assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); boolean found = false; RoleAssignment assignment; if (!isPlaybackMode()) { PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); } emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachineScaleSet .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); if (virtualMachineScaleSet.managedServiceIdentityType() != null) { Assertions .assertTrue(virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachineScaleSet.refresh(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); if (virtualMachineScaleSet.managedServiceIdentityType() != null) { Assertions .assertTrue(virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachineScaleSet .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet .managedServiceIdentityType() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); virtualMachineScaleSet.refresh(); Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet .managedServiceIdentityType() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachineScaleSet.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachineScaleSet.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet .managedServiceIdentityType() .equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); virtualMachineScaleSet.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachineScaleSet.managedServiceIdentityType()); Assertions .assertTrue( virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); virtualMachineScaleSet.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertEquals(0, virtualMachineScaleSet.userAssignedManagedServiceIdentityIds().size()); if (virtualMachineScaleSet.managedServiceIdentityType() != null) { Assertions .assertTrue(virtualMachineScaleSet.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); } @Test @Test public void canUpdateVirtualMachineScaleSetWithEMSIAndLMSI() throws Exception { String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); Network vmssNetwork = this .networkManager .networks() .define("vmssvnet") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAddressSpace("10.0.0.0/28") .withSubnet("subnet1", "10.0.0.0/28") .create(); LoadBalancer vmssInternalLoadBalancer = createInternalLoadBalancer(region, resourceGroup, vmssNetwork, "1"); VirtualMachineScaleSet virtualMachineScaleSet = this .computeManager .virtualMachineScaleSets() .define(vmssName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0) .withExistingPrimaryNetworkSubnet(vmssNetwork, "subnet1") .withoutPrimaryInternetFacingLoadBalancer() .withExistingPrimaryInternalLoadBalancer(vmssInternalLoadBalancer) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("jvuser") .withSsh(sshPublicKey()) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachineScaleSet = virtualMachineScaleSet.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachineScaleSet.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachineScaleSet.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachineScaleSet.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachineScaleSet = virtualMachineScaleSet .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachineScaleSet.innerModel().identity().userAssignedIdentities().keySet(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachineScaleSet.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachineScaleSet); Assertions.assertNotNull(virtualMachineScaleSet.innerModel()); Assertions.assertTrue(virtualMachineScaleSet.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachineScaleSet.systemAssignedManagedServiceIdentityTenantId()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
```suggestion if (isClient(metricName)) { return statusCode < 400; } ```
private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName) || (isServer(metricName) && captureHttpServer4xxAsError)) { return statusCode < 400; } if (isServer(metricName)) { return statusCode < 500; } return false; }
}
private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName)) { return statusCode < 400; } if (isServer(metricName)) { if (captureHttpServer4xxAsError) { return statusCode < 400; } return statusCode < 500; } return false; }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isClient(String metricName) { return metricName != null && metricName.contains(".client."); } private static boolean isServer(String metricName) { return metricName != null && metricName.contains(".server."); } }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isClient(String metricName) { return metricName.contains(".client."); } private static boolean isServer(String metricName) { return metricName.contains(".server."); } }
```suggestion if (isServer(metricName)) { return statusCode < 400 || (captureHttpServer4xxAsError && statusCode < 500); } ```
private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName) || (isServer(metricName) && captureHttpServer4xxAsError)) { return statusCode < 400; } if (isServer(metricName)) { return statusCode < 500; } return false; }
}
private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName)) { return statusCode < 400; } if (isServer(metricName)) { if (captureHttpServer4xxAsError) { return statusCode < 400; } return statusCode < 500; } return false; }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isClient(String metricName) { return metricName != null && metricName.contains(".client."); } private static boolean isServer(String metricName) { return metricName != null && metricName.contains(".server."); } }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isClient(String metricName) { return metricName.contains(".client."); } private static boolean isServer(String metricName) { return metricName.contains(".server."); } }
```suggestion return metricName.contains(".client."); ```
private static boolean isClient(String metricName) { return metricName != null && metricName.contains(".client."); }
return metricName != null && metricName.contains(".client.");
private static boolean isClient(String metricName) { return metricName.contains(".client."); }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName) || (isServer(metricName) && captureHttpServer4xxAsError)) { return statusCode < 400; } if (isServer(metricName)) { return statusCode < 500; } return false; } private static boolean isServer(String metricName) { return metricName != null && metricName.contains(".server."); } }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName)) { return statusCode < 400; } if (isServer(metricName)) { if (captureHttpServer4xxAsError) { return statusCode < 400; } return statusCode < 500; } return false; } private static boolean isServer(String metricName) { return metricName.contains(".server."); } }
```suggestion return metricName.contains(".server."); ```
private static boolean isServer(String metricName) { return metricName != null && metricName.contains(".server."); }
return metricName != null && metricName.contains(".server.");
private static boolean isServer(String metricName) { return metricName.contains(".server."); }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName) || (isServer(metricName) && captureHttpServer4xxAsError)) { return statusCode < 400; } if (isServer(metricName)) { return statusCode < 500; } return false; } private static boolean isClient(String metricName) { return metricName != null && metricName.contains(".client."); } }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set<String> OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES = new HashSet<>(4); public static final AttributeKey<String> APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME = AttributeKey.stringKey("applicationinsights.internal.metric_name"); private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final boolean captureHttpServer4xxAsError; static { OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.client.duration"); OTEL_UNSTABLE_METRICS_TO_EXCLUDE.add("rpc.server.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.server.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("http.client.request.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.client.duration"); OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.add("rpc.server.duration"); } public MetricDataMapper( BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, boolean captureHttpServer4xxAsError) { this.telemetryInitializer = telemetryInitializer; this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; } public void map(MetricData metricData, Consumer<TelemetryItem> consumer) { MetricDataType type = metricData.getType(); if (type == DOUBLE_SUM || type == DOUBLE_GAUGE || type == LONG_SUM || type == LONG_GAUGE || type == HISTOGRAM) { boolean isPreAggregatedStandardMetric = OTEL_PRE_AGGREGATED_STANDARD_METRIC_NAMES.contains(metricData.getName()); if (isPreAggregatedStandardMetric) { List<TelemetryItem> preAggregatedStandardMetrics = convertOtelMetricToAzureMonitorMetric(metricData, true); preAggregatedStandardMetrics.forEach(consumer::accept); } if (OTEL_UNSTABLE_METRICS_TO_EXCLUDE.contains(metricData.getName()) && metricData.getInstrumentationScopeInfo().getName().startsWith(OTEL_INSTRUMENTATION_NAME_PREFIX)) { return; } List<TelemetryItem> stableOtelMetrics = convertOtelMetricToAzureMonitorMetric(metricData, false); stableOtelMetrics.forEach(consumer::accept); } else { logger.warning("metric data type {} is not supported yet.", metricData.getType()); } } private List<TelemetryItem> convertOtelMetricToAzureMonitorMetric( MetricData metricData, boolean isPreAggregatedStandardMetric) { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (PointData pointData : metricData.getData().getPoints()) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(); telemetryInitializer.accept(builder, metricData.getResource()); builder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(pointData.getEpochNanos())); updateMetricPointBuilder( builder, metricData, pointData, captureHttpServer4xxAsError, isPreAggregatedStandardMetric); telemetryItems.add(builder.build()); } return telemetryItems; } public static void updateMetricPointBuilder( MetricTelemetryBuilder metricTelemetryBuilder, MetricData metricData, PointData pointData, boolean captureHttpServer4xxAsError, boolean isPreAggregatedStandardMetric) { checkArgument(metricData != null, "MetricData cannot be null."); MetricPointBuilder pointBuilder = new MetricPointBuilder(); MetricDataType type = metricData.getType(); double pointDataValue; switch (type) { case LONG_SUM: case LONG_GAUGE: pointDataValue = (double) ((LongPointData) pointData).getValue(); break; case DOUBLE_SUM: case DOUBLE_GAUGE: pointDataValue = ((DoublePointData) pointData).getValue(); break; case HISTOGRAM: long histogramCount = ((HistogramPointData) pointData).getCount(); if (histogramCount <= Integer.MAX_VALUE && histogramCount >= Integer.MIN_VALUE) { pointBuilder.setCount((int) histogramCount); } HistogramPointData histogramPointData = (HistogramPointData) pointData; double min = histogramPointData.getMin(); double max = histogramPointData.getMax(); if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { min = min * 1000; max = max * 1000; } pointDataValue = histogramPointData.getSum(); pointBuilder.setMin(min); pointBuilder.setMax(max); break; case SUMMARY: case EXPONENTIAL_HISTOGRAM: default: throw new IllegalArgumentException("metric data type '" + type + "' is not supported yet"); } if (shouldConvertToMilliseconds(metricData.getName(), isPreAggregatedStandardMetric)) { pointDataValue = pointDataValue * 1000; } pointBuilder.setValue(pointDataValue); String metricName = pointData.getAttributes().get(APPLICATIONINSIGHTS_INTERNAL_METRIC_NAME); if (metricName != null) { pointBuilder.setName(metricName); } else { pointBuilder.setName(metricData.getName()); } metricTelemetryBuilder.setMetricPoint(pointBuilder); Attributes attributes = pointData.getAttributes(); if (isPreAggregatedStandardMetric) { Long statusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); boolean success = isSuccess(metricData.getName(), statusCode, captureHttpServer4xxAsError); Boolean isSynthetic = attributes.get(IS_SYNTHETIC); attributes.forEach( (key, value) -> applyConnectionStringAndRoleNameOverrides( metricTelemetryBuilder, value, key.getKey())); if (isServer(metricData.getName())) { RequestExtractor.extract(metricTelemetryBuilder, statusCode, success, isSynthetic); } else if (isClient(metricData.getName())) { String dependencyType; int defaultPort; if (metricData.getName().startsWith("http")) { dependencyType = "Http"; defaultPort = getDefaultPortForHttpScheme(getStableOrOldAttribute(attributes, SemanticAttributes.URL_SCHEME, SemanticAttributes.HTTP_SCHEME)); } else { dependencyType = attributes.get(SemanticAttributes.RPC_SYSTEM); if (dependencyType == null) { dependencyType = "Unknown"; } defaultPort = Integer.MAX_VALUE; } String target = SpanDataMapper.getTargetOrDefault(attributes, defaultPort, dependencyType); DependencyExtractor.extract( metricTelemetryBuilder, statusCode, success, dependencyType, target, isSynthetic); } } else { MappingsBuilder mappingsBuilder = new MappingsBuilder(METRIC); mappingsBuilder.build().map(attributes, metricTelemetryBuilder); } } private static boolean shouldConvertToMilliseconds(String metricName, boolean isPreAggregatedStandardMetric) { return isPreAggregatedStandardMetric && (metricName.equals("http.server.request.duration") || metricName.equals("http.client.request.duration")); } private static boolean applyConnectionStringAndRoleNameOverrides( AbstractTelemetryBuilder telemetryBuilder, Object value, String key) { if (key.equals(AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey()) && value instanceof String) { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); return true; } if (key.equals(AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey()) && value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); return true; } return false; } private static int getDefaultPortForHttpScheme(@Nullable String httpScheme) { if (httpScheme == null) { return Integer.MAX_VALUE; } if (httpScheme.equals("https")) { return 443; } if (httpScheme.equals("http")) { return 80; } return Integer.MAX_VALUE; } private static boolean isSuccess(String metricName, Long statusCode, boolean captureHttpServer4xxAsError) { if (statusCode == null) { return true; } if (isClient(metricName)) { return statusCode < 400; } if (isServer(metricName)) { if (captureHttpServer4xxAsError) { return statusCode < 400; } return statusCode < 500; } return false; } private static boolean isClient(String metricName) { return metricName.contains(".client."); } }
it may be safer to use a thread local to prevent exporting our logs, e.g. to cover cases where our exporter calls azure sdk core classes which do their own verbose logging
public CompletableResultCode export(Collection<LogRecordData> logs) { if (stopped.get()) { return CompletableResultCode.ofFailure(); } List<TelemetryItem> telemetryItems = new ArrayList<>(); for (LogRecordData log : logs) { if (log.getInstrumentationScopeInfo().getName().startsWith(LOGGER_PREFIX)) { continue; } LOGGER.verbose("exporting log: {}", log); try { String stack = log.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); telemetryItems.add(mapper.map(log, stack, null)); OPERATION_LOGGER.recordSuccess(); } catch (Throwable t) { OPERATION_LOGGER.recordFailure(t.getMessage(), t, EXPORTER_MAPPING_ERROR); return CompletableResultCode.ofFailure(); } } return telemetryItemExporter.send(telemetryItems); }
}
public CompletableResultCode export(Collection<LogRecordData> logs) { if (stopped.get()) { return CompletableResultCode.ofFailure(); } List<TelemetryItem> telemetryItems = new ArrayList<>(); for (LogRecordData log : logs) { if (log.getInstrumentationScopeInfo().getName().startsWith(EXPORTER_LOGGER_PREFIX)) { continue; } LOGGER.verbose("exporting log: {}", log); try { String stack = log.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); telemetryItems.add(mapper.map(log, stack, null)); OPERATION_LOGGER.recordSuccess(); } catch (Throwable t) { OPERATION_LOGGER.recordFailure(t.getMessage(), t, EXPORTER_MAPPING_ERROR); return CompletableResultCode.ofFailure(); } } return telemetryItemExporter.send(telemetryItems); }
class AzureMonitorLogRecordExporter implements LogRecordExporter { private static final String LOGGER_PREFIX = "com.azure.monitor.opentelemetry.exporter"; private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorLogRecordExporter.class); private static final OperationLogger OPERATION_LOGGER = new OperationLogger(AzureMonitorLogRecordExporter.class, "Exporting log"); private final AtomicBoolean stopped = new AtomicBoolean(); private final LogDataMapper mapper; private final TelemetryItemExporter telemetryItemExporter; /** * Creates an instance of log exporter that is configured with given exporter client that sends * telemetry events to Application Insights resource identified by the instrumentation key. */ AzureMonitorLogRecordExporter(LogDataMapper mapper, TelemetryItemExporter telemetryItemExporter) { this.mapper = mapper; this.telemetryItemExporter = telemetryItemExporter; } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return telemetryItemExporter.flush(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { stopped.set(true); return telemetryItemExporter.shutdown(); } }
class AzureMonitorLogRecordExporter implements LogRecordExporter { private static final String EXPORTER_LOGGER_PREFIX = "com.azure.monitor.opentelemetry.exporter"; private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorLogRecordExporter.class); private static final OperationLogger OPERATION_LOGGER = new OperationLogger(AzureMonitorLogRecordExporter.class, "Exporting log"); private final AtomicBoolean stopped = new AtomicBoolean(); private final LogDataMapper mapper; private final TelemetryItemExporter telemetryItemExporter; /** * Creates an instance of log exporter that is configured with given exporter client that sends * telemetry events to Application Insights resource identified by the instrumentation key. */ AzureMonitorLogRecordExporter(LogDataMapper mapper, TelemetryItemExporter telemetryItemExporter) { this.mapper = mapper; this.telemetryItemExporter = telemetryItemExporter; } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return telemetryItemExporter.flush(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { stopped.set(true); return telemetryItemExporter.shutdown(); } }
let's keep as-is and in the future (once released) we can use https://github.com/open-telemetry/opentelemetry-java/pull/6546
public CompletableResultCode export(Collection<LogRecordData> logs) { if (stopped.get()) { return CompletableResultCode.ofFailure(); } List<TelemetryItem> telemetryItems = new ArrayList<>(); for (LogRecordData log : logs) { if (log.getInstrumentationScopeInfo().getName().startsWith(LOGGER_PREFIX)) { continue; } LOGGER.verbose("exporting log: {}", log); try { String stack = log.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); telemetryItems.add(mapper.map(log, stack, null)); OPERATION_LOGGER.recordSuccess(); } catch (Throwable t) { OPERATION_LOGGER.recordFailure(t.getMessage(), t, EXPORTER_MAPPING_ERROR); return CompletableResultCode.ofFailure(); } } return telemetryItemExporter.send(telemetryItems); }
}
public CompletableResultCode export(Collection<LogRecordData> logs) { if (stopped.get()) { return CompletableResultCode.ofFailure(); } List<TelemetryItem> telemetryItems = new ArrayList<>(); for (LogRecordData log : logs) { if (log.getInstrumentationScopeInfo().getName().startsWith(EXPORTER_LOGGER_PREFIX)) { continue; } LOGGER.verbose("exporting log: {}", log); try { String stack = log.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); telemetryItems.add(mapper.map(log, stack, null)); OPERATION_LOGGER.recordSuccess(); } catch (Throwable t) { OPERATION_LOGGER.recordFailure(t.getMessage(), t, EXPORTER_MAPPING_ERROR); return CompletableResultCode.ofFailure(); } } return telemetryItemExporter.send(telemetryItems); }
class AzureMonitorLogRecordExporter implements LogRecordExporter { private static final String LOGGER_PREFIX = "com.azure.monitor.opentelemetry.exporter"; private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorLogRecordExporter.class); private static final OperationLogger OPERATION_LOGGER = new OperationLogger(AzureMonitorLogRecordExporter.class, "Exporting log"); private final AtomicBoolean stopped = new AtomicBoolean(); private final LogDataMapper mapper; private final TelemetryItemExporter telemetryItemExporter; /** * Creates an instance of log exporter that is configured with given exporter client that sends * telemetry events to Application Insights resource identified by the instrumentation key. */ AzureMonitorLogRecordExporter(LogDataMapper mapper, TelemetryItemExporter telemetryItemExporter) { this.mapper = mapper; this.telemetryItemExporter = telemetryItemExporter; } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return telemetryItemExporter.flush(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { stopped.set(true); return telemetryItemExporter.shutdown(); } }
class AzureMonitorLogRecordExporter implements LogRecordExporter { private static final String EXPORTER_LOGGER_PREFIX = "com.azure.monitor.opentelemetry.exporter"; private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorLogRecordExporter.class); private static final OperationLogger OPERATION_LOGGER = new OperationLogger(AzureMonitorLogRecordExporter.class, "Exporting log"); private final AtomicBoolean stopped = new AtomicBoolean(); private final LogDataMapper mapper; private final TelemetryItemExporter telemetryItemExporter; /** * Creates an instance of log exporter that is configured with given exporter client that sends * telemetry events to Application Insights resource identified by the instrumentation key. */ AzureMonitorLogRecordExporter(LogDataMapper mapper, TelemetryItemExporter telemetryItemExporter) { this.mapper = mapper; this.telemetryItemExporter = telemetryItemExporter; } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return telemetryItemExporter.flush(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { stopped.set(true); return telemetryItemExporter.shutdown(); } }
i added a todo for reminder
public CompletableResultCode export(Collection<LogRecordData> logs) { if (stopped.get()) { return CompletableResultCode.ofFailure(); } List<TelemetryItem> telemetryItems = new ArrayList<>(); for (LogRecordData log : logs) { if (log.getInstrumentationScopeInfo().getName().startsWith(LOGGER_PREFIX)) { continue; } LOGGER.verbose("exporting log: {}", log); try { String stack = log.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); telemetryItems.add(mapper.map(log, stack, null)); OPERATION_LOGGER.recordSuccess(); } catch (Throwable t) { OPERATION_LOGGER.recordFailure(t.getMessage(), t, EXPORTER_MAPPING_ERROR); return CompletableResultCode.ofFailure(); } } return telemetryItemExporter.send(telemetryItems); }
}
public CompletableResultCode export(Collection<LogRecordData> logs) { if (stopped.get()) { return CompletableResultCode.ofFailure(); } List<TelemetryItem> telemetryItems = new ArrayList<>(); for (LogRecordData log : logs) { if (log.getInstrumentationScopeInfo().getName().startsWith(EXPORTER_LOGGER_PREFIX)) { continue; } LOGGER.verbose("exporting log: {}", log); try { String stack = log.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); telemetryItems.add(mapper.map(log, stack, null)); OPERATION_LOGGER.recordSuccess(); } catch (Throwable t) { OPERATION_LOGGER.recordFailure(t.getMessage(), t, EXPORTER_MAPPING_ERROR); return CompletableResultCode.ofFailure(); } } return telemetryItemExporter.send(telemetryItems); }
class AzureMonitorLogRecordExporter implements LogRecordExporter { private static final String LOGGER_PREFIX = "com.azure.monitor.opentelemetry.exporter"; private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorLogRecordExporter.class); private static final OperationLogger OPERATION_LOGGER = new OperationLogger(AzureMonitorLogRecordExporter.class, "Exporting log"); private final AtomicBoolean stopped = new AtomicBoolean(); private final LogDataMapper mapper; private final TelemetryItemExporter telemetryItemExporter; /** * Creates an instance of log exporter that is configured with given exporter client that sends * telemetry events to Application Insights resource identified by the instrumentation key. */ AzureMonitorLogRecordExporter(LogDataMapper mapper, TelemetryItemExporter telemetryItemExporter) { this.mapper = mapper; this.telemetryItemExporter = telemetryItemExporter; } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return telemetryItemExporter.flush(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { stopped.set(true); return telemetryItemExporter.shutdown(); } }
class AzureMonitorLogRecordExporter implements LogRecordExporter { private static final String EXPORTER_LOGGER_PREFIX = "com.azure.monitor.opentelemetry.exporter"; private static final ClientLogger LOGGER = new ClientLogger(AzureMonitorLogRecordExporter.class); private static final OperationLogger OPERATION_LOGGER = new OperationLogger(AzureMonitorLogRecordExporter.class, "Exporting log"); private final AtomicBoolean stopped = new AtomicBoolean(); private final LogDataMapper mapper; private final TelemetryItemExporter telemetryItemExporter; /** * Creates an instance of log exporter that is configured with given exporter client that sends * telemetry events to Application Insights resource identified by the instrumentation key. */ AzureMonitorLogRecordExporter(LogDataMapper mapper, TelemetryItemExporter telemetryItemExporter) { this.mapper = mapper; this.telemetryItemExporter = telemetryItemExporter; } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return telemetryItemExporter.flush(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { stopped.set(true); return telemetryItemExporter.shutdown(); } }
If `content` can be `null` I think this will still need `reader.getNullable`. But I think this needs more logic here if the content can be null, string, array, or object. ```java if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_OBJECT) { content = BinaryData.fromObject(reader.readMap(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.START_ARRAY)) { content = BinaryData.fromObject(reader.readArray(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { // invalid state? Probably throw? } ``` Unless when the String constructor is used in this class it's expected to be the raw JSON for a JSON object of ChatMessageContentItem or JSON array of ChatMessageContentItem.
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { content = BinaryData.fromBytes(reader.getBinary()); } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
content = BinaryData.fromBytes(reader.getBinary());
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject( reader.readArray(arrayReader -> arrayReader.readObject(ChatMessageContentItem::fromJson))); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected 'content' type found when deserializing" + " ChatRequestUserMessage JSON object: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this(BinaryData.fromString(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this(BinaryData.fromObject(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this(BinaryData.fromObject(content)); } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeBinaryField("content", this.content.toBytes()); jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; private final String stringContent; private final List<ChatMessageContentItem> chatMessageContentItems; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; this.stringContent = null; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this.content = BinaryData.fromString(content); this.stringContent = content; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this.content = BinaryData.fromObject(content); this.chatMessageContentItems = Arrays.asList(content); this.stringContent = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this.content = BinaryData.fromObject(content); this.stringContent = null; this.chatMessageContentItems = content; } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); if (stringContent != null) { jsonWriter.writeStringField("content", stringContent); } else if (chatMessageContentItems != null) { jsonWriter.writeArrayField("content", chatMessageContentItems, JsonWriter::writeJson); } jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
We should have a bit more context in the exception message. We should mention that we are trying to deserialize ChatRequestUserMessage and the "content" field had an unexpected token.
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_OBJECT) { content = BinaryData.fromObject(reader.readMap(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject(reader.readArray(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected token: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
throw new IllegalStateException("Unexpected token: " + reader.currentToken());
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject( reader.readArray(arrayReader -> arrayReader.readObject(ChatMessageContentItem::fromJson))); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected 'content' type found when deserializing" + " ChatRequestUserMessage JSON object: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this(BinaryData.fromString(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this(BinaryData.fromObject(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this(BinaryData.fromObject(content)); } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeUntypedField("content", this.content); jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; private final String stringContent; private final List<ChatMessageContentItem> chatMessageContentItems; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; this.stringContent = null; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this.content = BinaryData.fromString(content); this.stringContent = content; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this.content = BinaryData.fromObject(content); this.chatMessageContentItems = Arrays.asList(content); this.stringContent = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this.content = BinaryData.fromObject(content); this.stringContent = null; this.chatMessageContentItems = content; } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); if (stringContent != null) { jsonWriter.writeStringField("content", stringContent); } else if (chatMessageContentItems != null) { jsonWriter.writeArrayField("content", chatMessageContentItems, JsonWriter::writeJson); } jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
Are string, object and arrays the only types of content we can have?
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_OBJECT) { content = BinaryData.fromObject(reader.readMap(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject(reader.readArray(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected token: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
content = null;
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject( reader.readArray(arrayReader -> arrayReader.readObject(ChatMessageContentItem::fromJson))); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected 'content' type found when deserializing" + " ChatRequestUserMessage JSON object: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this(BinaryData.fromString(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this(BinaryData.fromObject(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this(BinaryData.fromObject(content)); } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeUntypedField("content", this.content); jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; private final String stringContent; private final List<ChatMessageContentItem> chatMessageContentItems; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; this.stringContent = null; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this.content = BinaryData.fromString(content); this.stringContent = content; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this.content = BinaryData.fromObject(content); this.chatMessageContentItems = Arrays.asList(content); this.stringContent = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this.content = BinaryData.fromObject(content); this.stringContent = null; this.chatMessageContentItems = content; } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); if (stringContent != null) { jsonWriter.writeStringField("content", stringContent); } else if (chatMessageContentItems != null) { jsonWriter.writeArrayField("content", chatMessageContentItems, JsonWriter::writeJson); } jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
Yeah. We have String, arrays(Array and List), Object(BinaryDatra) only https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestUserMessage.java#L35-L70
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_OBJECT) { content = BinaryData.fromObject(reader.readMap(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject(reader.readArray(JsonReader::readUntyped)); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected token: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
content = null;
public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BinaryData content = null; ChatRole role = ChatRole.USER; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("content".equals(fieldName)) { if (reader.currentToken() == JsonToken.STRING) { content = BinaryData.fromString(reader.getString()); } else if (reader.currentToken() == JsonToken.START_ARRAY) { content = BinaryData.fromObject( reader.readArray(arrayReader -> arrayReader.readObject(ChatMessageContentItem::fromJson))); } else if (reader.currentToken() == JsonToken.NULL) { content = null; } else { throw new IllegalStateException("Unexpected 'content' type found when deserializing" + " ChatRequestUserMessage JSON object: " + reader.currentToken()); } } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); } else if ("name".equals(fieldName)) { name = reader.getString(); } else { reader.skipChildren(); } } ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); deserializedChatRequestUserMessage.role = role; deserializedChatRequestUserMessage.name = name; return deserializedChatRequestUserMessage; }); }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this(BinaryData.fromString(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this(BinaryData.fromObject(content)); } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this(BinaryData.fromObject(content)); } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeUntypedField("content", this.content); jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
class ChatRequestUserMessage extends ChatRequestMessage { /* * The contents of the user message, with available input types varying by selected model. */ @Generated private final BinaryData content; private final String stringContent; private final List<ChatMessageContentItem> chatMessageContentItems; /* * An optional name for the participant. */ @Generated private String name; /** * Creates an instance of ChatRequestUserMessage class. * * @param content the content value to set. */ private ChatRequestUserMessage(BinaryData content) { this.content = content; this.stringContent = null; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using plain text content. * * @param content The plain text content associated with the message. */ public ChatRequestUserMessage(String content) { this.content = BinaryData.fromString(content); this.stringContent = content; this.chatMessageContentItems = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(ChatMessageContentItem[] content) { this.content = BinaryData.fromObject(content); this.chatMessageContentItems = Arrays.asList(content); this.stringContent = null; } /** * Creates a new instance of ChatRequestUserMessage using a collection of structured content. * * @param content The collection of structured content associated with the message. */ public ChatRequestUserMessage(List<ChatMessageContentItem> content) { this.content = BinaryData.fromObject(content); this.stringContent = null; this.chatMessageContentItems = content; } /** * Get the content property: The contents of the user message, with available input types varying by selected model. * * @return the content value. */ @Generated public BinaryData getContent() { return this.content; } /** * Get the name property: An optional name for the participant. * * @return the name value. */ @Generated public String getName() { return this.name; } /** * Set the name property: An optional name for the participant. * * @param name the name value to set. * @return the ChatRequestUserMessage object itself. */ @Generated public ChatRequestUserMessage setName(String name) { this.name = name; return this; } /* * The chat role associated with this message. */ @Generated private ChatRole role = ChatRole.USER; /** * Get the role property: The chat role associated with this message. * * @return the role value. */ @Generated @Override public ChatRole getRole() { return this.role; } /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); if (stringContent != null) { jsonWriter.writeStringField("content", stringContent); } else if (chatMessageContentItems != null) { jsonWriter.writeArrayField("content", chatMessageContentItems, JsonWriter::writeJson); } jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); jsonWriter.writeStringField("name", this.name); return jsonWriter.writeEndObject(); } /** * Reads an instance of ChatRequestUserMessage from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of ChatRequestUserMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ChatRequestUserMessage. */ }
What is this?
public static TokenCredential getTokenCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } else if (interceptorManager.isRecordMode()){ return new DefaultAzureCredentialBuilder().build(); } else { Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); builder.addLast(request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic())); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN");
public static TokenCredential getTokenCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } else if (interceptorManager.isRecordMode()){ return new DefaultAzureCredentialBuilder().build(); } else { Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); builder.addLast(request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic())); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
class StorageCommonTestUtils { public static final TestEnvironment ENVIRONMENT = TestEnvironment.getInstance(); private static final HttpClient NETTY_HTTP_CLIENT = new NettyAsyncHttpClientProvider().createInstance(); private static final HttpClient OK_HTTP_CLIENT = new OkHttpAsyncClientProvider().createInstance(); private static final HttpClient VERTX_HTTP_CLIENT = new VertxAsyncHttpClientProvider().createInstance(); private static final HttpClient JDK_HTTP_HTTP_CLIENT; static { HttpClient jdkHttpHttpClient; try { jdkHttpHttpClient = createJdkHttpClient(); } catch (LinkageError | ReflectiveOperationException e) { jdkHttpHttpClient = null; } JDK_HTTP_HTTP_CLIENT = jdkHttpHttpClient; } @SuppressWarnings("deprecation") private static HttpClient createJdkHttpClient() throws ReflectiveOperationException { Class<?> clazz = Class.forName("com.azure.core.http.jdk.httpclient.JdkHttpClientProvider"); return (HttpClient) clazz.getDeclaredMethod("createInstance").invoke(clazz.newInstance()); } /** * Gets the CRC32 for the given string. * * @param input The string to get the CRC32 for. * @return The CRC32. */ public static String getCrc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(StandardCharsets.UTF_8)); return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase(); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param playbackClientSupplier Supplier for the playback client. * @return An HttpClient instance. */ public static HttpClient getHttpClient(Supplier<HttpClient> playbackClientSupplier) { if (ENVIRONMENT.getTestMode() != TestMode.PLAYBACK) { switch (ENVIRONMENT.getHttpClientType()) { case NETTY: return NETTY_HTTP_CLIENT; case OK_HTTP: return OK_HTTP_CLIENT; case VERTX: return VERTX_HTTP_CLIENT; case JDK_HTTP: return JDK_HTTP_HTTP_CLIENT; default: throw new IllegalArgumentException("Unknown http client type: " + ENVIRONMENT.getHttpClientType()); } } else { return playbackClientSupplier.get(); } } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream) { return convertInputStreamToByteArray(inputStream, 4096); } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @param expectedSize The expected size of the byte array. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream, int expectedSize) { byte[] buffer = new byte[4096]; int b; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedSize); try { while ((b = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, b); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return outputStream.toByteArray(); } /** * Compares two files for having equivalent content. * * @param file1 File used to upload data to the service * @param file2 File used to download data from the service * @param offset Write offset from the upload file * @param count Size of the download from the service * @return Whether the files have equivalent content based on offset and read count */ public static boolean compareFiles(File file1, File file2, long offset, long count) throws IOException { long pos = 0L; int defaultBufferSize = 128 * Constants.KB; FileInputStream stream1 = new FileInputStream(file1); stream1.skip(offset); FileInputStream stream2 = new FileInputStream(file2); try { int bufferSize = (int) Math.min(defaultBufferSize, count); while (pos < count) { int expectedReadCount = (int) Math.min(bufferSize, count - pos); byte[] buffer1 = new byte[expectedReadCount]; byte[] buffer2 = new byte[expectedReadCount]; int readCount1 = stream1.read(buffer1); int readCount2 = stream2.read(buffer2); TestUtils.assertArraysEqual(buffer1, buffer2); assertEquals(readCount1, readCount2); pos += expectedReadCount; } int verificationRead = stream2.read(); return pos == count && verificationRead == -1; } finally { stream1.close(); stream2.close(); } } /** * Instruments a builder with the test interceptor manager. * * @param builder The builder to instrument. * @param interceptorManager The interceptor manager to use. * @param <T> The type of the builder. * @param <E> The type of the service version. * @return The instrumented builder. */ @SuppressWarnings("unchecked") public static <T extends HttpTrait<T>, E extends Enum<E>> T instrument(T builder, HttpLogOptions logOptions, InterceptorManager interceptorManager) { builder.httpClient(getHttpClient(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (ENVIRONMENT.getServiceVersion() != null) { try { Method serviceVersionMethod = Arrays.stream(builder.getClass().getDeclaredMethods()) .filter(method -> "serviceVersion".equals(method.getName()) && method.getParameterCount() == 1 && ServiceVersion.class.isAssignableFrom(method.getParameterTypes()[0])) .findFirst() .orElseThrow(() -> new RuntimeException("Unable to find serviceVersion method for builder: " + builder.getClass())); Class<E> serviceVersionClass = (Class<E>) serviceVersionMethod.getParameterTypes()[0]; ServiceVersion serviceVersion = (ServiceVersion) Enum.valueOf(serviceVersionClass, ENVIRONMENT.getServiceVersion()); serviceVersionMethod.invoke(builder, serviceVersion); builder.addPolicy(new ServiceVersionValidationPolicy(serviceVersion.getVersion())); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } return builder.httpLogOptions(logOptions); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param interceptorManager The interceptor manager to use. * @return An HttpClient instance. */ public static HttpClient getHttpClient(InterceptorManager interceptorManager) { return StorageCommonTestUtils.getHttpClient(interceptorManager::getPlaybackClient); } /** * Gets a random byte array of the given size. * * @param size The size of the byte array. * @param testResourceNamer The test resource namer to use. * @return The random byte array. */ public static byte[] getRandomByteArray(int size, TestResourceNamer testResourceNamer) { long seed = UUID.fromString(testResourceNamer.randomUuid()).getMostSignificantBits() & Long.MAX_VALUE; Random rand = new Random(seed); byte[] data = new byte[size]; rand.nextBytes(data); return data; } /** * Gets a random ByteBuffer of the given size. * * @param size The size of the ByteBuffer. * @param testResourceNamer The test resource namer to use. * @return The random ByteBuffer. */ public static ByteBuffer getRandomData(int size, TestResourceNamer testResourceNamer) { return ByteBuffer.wrap(getRandomByteArray(size, testResourceNamer)); } /** * Gets a random file of the given size. * * @param size The size of the file. * @param testResourceNamer The test resource namer to use. * @return The random file. * @throws IOException If an I/O error occurs. */ public static File getRandomFile(int size, TestResourceNamer testResourceNamer) throws IOException { try { File file = File.createTempFile(CoreUtils.randomUuid().toString(), ".txt"); file.deleteOnExit(); if (size > Constants.MB) { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] data = getRandomByteArray(Constants.MB, testResourceNamer); int mbChunks = size / Constants.MB; int remaining = size % Constants.MB; for (int i = 0; i < mbChunks; i++) { fos.write(data); } if (remaining > 0) { fos.write(data, 0, remaining); } } } else { Files.write(file.toPath(), getRandomByteArray(size, testResourceNamer)); } return file; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Gets token credentials for a test. * * @param interceptorManager The interceptor manager to use. * @return The TokenCredential to use. */ }
class StorageCommonTestUtils { public static final TestEnvironment ENVIRONMENT = TestEnvironment.getInstance(); private static final HttpClient NETTY_HTTP_CLIENT = new NettyAsyncHttpClientProvider().createInstance(); private static final HttpClient OK_HTTP_CLIENT = new OkHttpAsyncClientProvider().createInstance(); private static final HttpClient VERTX_HTTP_CLIENT = new VertxAsyncHttpClientProvider().createInstance(); private static final HttpClient JDK_HTTP_HTTP_CLIENT; static { HttpClient jdkHttpHttpClient; try { jdkHttpHttpClient = createJdkHttpClient(); } catch (LinkageError | ReflectiveOperationException e) { jdkHttpHttpClient = null; } JDK_HTTP_HTTP_CLIENT = jdkHttpHttpClient; } @SuppressWarnings("deprecation") private static HttpClient createJdkHttpClient() throws ReflectiveOperationException { Class<?> clazz = Class.forName("com.azure.core.http.jdk.httpclient.JdkHttpClientProvider"); return (HttpClient) clazz.getDeclaredMethod("createInstance").invoke(clazz.newInstance()); } /** * Gets the CRC32 for the given string. * * @param input The string to get the CRC32 for. * @return The CRC32. */ public static String getCrc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(StandardCharsets.UTF_8)); return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase(); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param playbackClientSupplier Supplier for the playback client. * @return An HttpClient instance. */ public static HttpClient getHttpClient(Supplier<HttpClient> playbackClientSupplier) { if (ENVIRONMENT.getTestMode() != TestMode.PLAYBACK) { switch (ENVIRONMENT.getHttpClientType()) { case NETTY: return NETTY_HTTP_CLIENT; case OK_HTTP: return OK_HTTP_CLIENT; case VERTX: return VERTX_HTTP_CLIENT; case JDK_HTTP: return JDK_HTTP_HTTP_CLIENT; default: throw new IllegalArgumentException("Unknown http client type: " + ENVIRONMENT.getHttpClientType()); } } else { return playbackClientSupplier.get(); } } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream) { return convertInputStreamToByteArray(inputStream, 4096); } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @param expectedSize The expected size of the byte array. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream, int expectedSize) { byte[] buffer = new byte[4096]; int b; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedSize); try { while ((b = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, b); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return outputStream.toByteArray(); } /** * Compares two files for having equivalent content. * * @param file1 File used to upload data to the service * @param file2 File used to download data from the service * @param offset Write offset from the upload file * @param count Size of the download from the service * @return Whether the files have equivalent content based on offset and read count */ public static boolean compareFiles(File file1, File file2, long offset, long count) throws IOException { long pos = 0L; int defaultBufferSize = 128 * Constants.KB; FileInputStream stream1 = new FileInputStream(file1); stream1.skip(offset); FileInputStream stream2 = new FileInputStream(file2); try { int bufferSize = (int) Math.min(defaultBufferSize, count); while (pos < count) { int expectedReadCount = (int) Math.min(bufferSize, count - pos); byte[] buffer1 = new byte[expectedReadCount]; byte[] buffer2 = new byte[expectedReadCount]; int readCount1 = stream1.read(buffer1); int readCount2 = stream2.read(buffer2); TestUtils.assertArraysEqual(buffer1, buffer2); assertEquals(readCount1, readCount2); pos += expectedReadCount; } int verificationRead = stream2.read(); return pos == count && verificationRead == -1; } finally { stream1.close(); stream2.close(); } } /** * Instruments a builder with the test interceptor manager. * * @param builder The builder to instrument. * @param interceptorManager The interceptor manager to use. * @param <T> The type of the builder. * @param <E> The type of the service version. * @return The instrumented builder. */ @SuppressWarnings("unchecked") public static <T extends HttpTrait<T>, E extends Enum<E>> T instrument(T builder, HttpLogOptions logOptions, InterceptorManager interceptorManager) { builder.httpClient(getHttpClient(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (ENVIRONMENT.getServiceVersion() != null) { try { Method serviceVersionMethod = Arrays.stream(builder.getClass().getDeclaredMethods()) .filter(method -> "serviceVersion".equals(method.getName()) && method.getParameterCount() == 1 && ServiceVersion.class.isAssignableFrom(method.getParameterTypes()[0])) .findFirst() .orElseThrow(() -> new RuntimeException("Unable to find serviceVersion method for builder: " + builder.getClass())); Class<E> serviceVersionClass = (Class<E>) serviceVersionMethod.getParameterTypes()[0]; ServiceVersion serviceVersion = (ServiceVersion) Enum.valueOf(serviceVersionClass, ENVIRONMENT.getServiceVersion()); serviceVersionMethod.invoke(builder, serviceVersion); builder.addPolicy(new ServiceVersionValidationPolicy(serviceVersion.getVersion())); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } return builder.httpLogOptions(logOptions); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param interceptorManager The interceptor manager to use. * @return An HttpClient instance. */ public static HttpClient getHttpClient(InterceptorManager interceptorManager) { return StorageCommonTestUtils.getHttpClient(interceptorManager::getPlaybackClient); } /** * Gets a random byte array of the given size. * * @param size The size of the byte array. * @param testResourceNamer The test resource namer to use. * @return The random byte array. */ public static byte[] getRandomByteArray(int size, TestResourceNamer testResourceNamer) { long seed = UUID.fromString(testResourceNamer.randomUuid()).getMostSignificantBits() & Long.MAX_VALUE; Random rand = new Random(seed); byte[] data = new byte[size]; rand.nextBytes(data); return data; } /** * Gets a random ByteBuffer of the given size. * * @param size The size of the ByteBuffer. * @param testResourceNamer The test resource namer to use. * @return The random ByteBuffer. */ public static ByteBuffer getRandomData(int size, TestResourceNamer testResourceNamer) { return ByteBuffer.wrap(getRandomByteArray(size, testResourceNamer)); } /** * Gets a random file of the given size. * * @param size The size of the file. * @param testResourceNamer The test resource namer to use. * @return The random file. * @throws IOException If an I/O error occurs. */ public static File getRandomFile(int size, TestResourceNamer testResourceNamer) throws IOException { try { File file = File.createTempFile(CoreUtils.randomUuid().toString(), ".txt"); file.deleteOnExit(); if (size > Constants.MB) { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] data = getRandomByteArray(Constants.MB, testResourceNamer); int mbChunks = size / Constants.MB; int remaining = size % Constants.MB; for (int i = 0; i < mbChunks; i++) { fos.write(data); } if (remaining > 0) { fos.write(data, 0, remaining); } } } else { Files.write(file.toPath(), getRandomByteArray(size, testResourceNamer)); } return file; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Gets token credentials for a test. * * @param interceptorManager The interceptor manager to use. * @return The TokenCredential to use. */ }
This is how we authenticate using AzurePipelinesCredential
public static TokenCredential getTokenCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } else if (interceptorManager.isRecordMode()){ return new DefaultAzureCredentialBuilder().build(); } else { Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); builder.addLast(request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic())); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN");
public static TokenCredential getTokenCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } else if (interceptorManager.isRecordMode()){ return new DefaultAzureCredentialBuilder().build(); } else { Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); builder.addLast(request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic())); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
class StorageCommonTestUtils { public static final TestEnvironment ENVIRONMENT = TestEnvironment.getInstance(); private static final HttpClient NETTY_HTTP_CLIENT = new NettyAsyncHttpClientProvider().createInstance(); private static final HttpClient OK_HTTP_CLIENT = new OkHttpAsyncClientProvider().createInstance(); private static final HttpClient VERTX_HTTP_CLIENT = new VertxAsyncHttpClientProvider().createInstance(); private static final HttpClient JDK_HTTP_HTTP_CLIENT; static { HttpClient jdkHttpHttpClient; try { jdkHttpHttpClient = createJdkHttpClient(); } catch (LinkageError | ReflectiveOperationException e) { jdkHttpHttpClient = null; } JDK_HTTP_HTTP_CLIENT = jdkHttpHttpClient; } @SuppressWarnings("deprecation") private static HttpClient createJdkHttpClient() throws ReflectiveOperationException { Class<?> clazz = Class.forName("com.azure.core.http.jdk.httpclient.JdkHttpClientProvider"); return (HttpClient) clazz.getDeclaredMethod("createInstance").invoke(clazz.newInstance()); } /** * Gets the CRC32 for the given string. * * @param input The string to get the CRC32 for. * @return The CRC32. */ public static String getCrc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(StandardCharsets.UTF_8)); return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase(); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param playbackClientSupplier Supplier for the playback client. * @return An HttpClient instance. */ public static HttpClient getHttpClient(Supplier<HttpClient> playbackClientSupplier) { if (ENVIRONMENT.getTestMode() != TestMode.PLAYBACK) { switch (ENVIRONMENT.getHttpClientType()) { case NETTY: return NETTY_HTTP_CLIENT; case OK_HTTP: return OK_HTTP_CLIENT; case VERTX: return VERTX_HTTP_CLIENT; case JDK_HTTP: return JDK_HTTP_HTTP_CLIENT; default: throw new IllegalArgumentException("Unknown http client type: " + ENVIRONMENT.getHttpClientType()); } } else { return playbackClientSupplier.get(); } } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream) { return convertInputStreamToByteArray(inputStream, 4096); } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @param expectedSize The expected size of the byte array. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream, int expectedSize) { byte[] buffer = new byte[4096]; int b; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedSize); try { while ((b = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, b); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return outputStream.toByteArray(); } /** * Compares two files for having equivalent content. * * @param file1 File used to upload data to the service * @param file2 File used to download data from the service * @param offset Write offset from the upload file * @param count Size of the download from the service * @return Whether the files have equivalent content based on offset and read count */ public static boolean compareFiles(File file1, File file2, long offset, long count) throws IOException { long pos = 0L; int defaultBufferSize = 128 * Constants.KB; FileInputStream stream1 = new FileInputStream(file1); stream1.skip(offset); FileInputStream stream2 = new FileInputStream(file2); try { int bufferSize = (int) Math.min(defaultBufferSize, count); while (pos < count) { int expectedReadCount = (int) Math.min(bufferSize, count - pos); byte[] buffer1 = new byte[expectedReadCount]; byte[] buffer2 = new byte[expectedReadCount]; int readCount1 = stream1.read(buffer1); int readCount2 = stream2.read(buffer2); TestUtils.assertArraysEqual(buffer1, buffer2); assertEquals(readCount1, readCount2); pos += expectedReadCount; } int verificationRead = stream2.read(); return pos == count && verificationRead == -1; } finally { stream1.close(); stream2.close(); } } /** * Instruments a builder with the test interceptor manager. * * @param builder The builder to instrument. * @param interceptorManager The interceptor manager to use. * @param <T> The type of the builder. * @param <E> The type of the service version. * @return The instrumented builder. */ @SuppressWarnings("unchecked") public static <T extends HttpTrait<T>, E extends Enum<E>> T instrument(T builder, HttpLogOptions logOptions, InterceptorManager interceptorManager) { builder.httpClient(getHttpClient(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (ENVIRONMENT.getServiceVersion() != null) { try { Method serviceVersionMethod = Arrays.stream(builder.getClass().getDeclaredMethods()) .filter(method -> "serviceVersion".equals(method.getName()) && method.getParameterCount() == 1 && ServiceVersion.class.isAssignableFrom(method.getParameterTypes()[0])) .findFirst() .orElseThrow(() -> new RuntimeException("Unable to find serviceVersion method for builder: " + builder.getClass())); Class<E> serviceVersionClass = (Class<E>) serviceVersionMethod.getParameterTypes()[0]; ServiceVersion serviceVersion = (ServiceVersion) Enum.valueOf(serviceVersionClass, ENVIRONMENT.getServiceVersion()); serviceVersionMethod.invoke(builder, serviceVersion); builder.addPolicy(new ServiceVersionValidationPolicy(serviceVersion.getVersion())); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } return builder.httpLogOptions(logOptions); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param interceptorManager The interceptor manager to use. * @return An HttpClient instance. */ public static HttpClient getHttpClient(InterceptorManager interceptorManager) { return StorageCommonTestUtils.getHttpClient(interceptorManager::getPlaybackClient); } /** * Gets a random byte array of the given size. * * @param size The size of the byte array. * @param testResourceNamer The test resource namer to use. * @return The random byte array. */ public static byte[] getRandomByteArray(int size, TestResourceNamer testResourceNamer) { long seed = UUID.fromString(testResourceNamer.randomUuid()).getMostSignificantBits() & Long.MAX_VALUE; Random rand = new Random(seed); byte[] data = new byte[size]; rand.nextBytes(data); return data; } /** * Gets a random ByteBuffer of the given size. * * @param size The size of the ByteBuffer. * @param testResourceNamer The test resource namer to use. * @return The random ByteBuffer. */ public static ByteBuffer getRandomData(int size, TestResourceNamer testResourceNamer) { return ByteBuffer.wrap(getRandomByteArray(size, testResourceNamer)); } /** * Gets a random file of the given size. * * @param size The size of the file. * @param testResourceNamer The test resource namer to use. * @return The random file. * @throws IOException If an I/O error occurs. */ public static File getRandomFile(int size, TestResourceNamer testResourceNamer) throws IOException { try { File file = File.createTempFile(CoreUtils.randomUuid().toString(), ".txt"); file.deleteOnExit(); if (size > Constants.MB) { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] data = getRandomByteArray(Constants.MB, testResourceNamer); int mbChunks = size / Constants.MB; int remaining = size % Constants.MB; for (int i = 0; i < mbChunks; i++) { fos.write(data); } if (remaining > 0) { fos.write(data, 0, remaining); } } } else { Files.write(file.toPath(), getRandomByteArray(size, testResourceNamer)); } return file; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Gets token credentials for a test. * * @param interceptorManager The interceptor manager to use. * @return The TokenCredential to use. */ }
class StorageCommonTestUtils { public static final TestEnvironment ENVIRONMENT = TestEnvironment.getInstance(); private static final HttpClient NETTY_HTTP_CLIENT = new NettyAsyncHttpClientProvider().createInstance(); private static final HttpClient OK_HTTP_CLIENT = new OkHttpAsyncClientProvider().createInstance(); private static final HttpClient VERTX_HTTP_CLIENT = new VertxAsyncHttpClientProvider().createInstance(); private static final HttpClient JDK_HTTP_HTTP_CLIENT; static { HttpClient jdkHttpHttpClient; try { jdkHttpHttpClient = createJdkHttpClient(); } catch (LinkageError | ReflectiveOperationException e) { jdkHttpHttpClient = null; } JDK_HTTP_HTTP_CLIENT = jdkHttpHttpClient; } @SuppressWarnings("deprecation") private static HttpClient createJdkHttpClient() throws ReflectiveOperationException { Class<?> clazz = Class.forName("com.azure.core.http.jdk.httpclient.JdkHttpClientProvider"); return (HttpClient) clazz.getDeclaredMethod("createInstance").invoke(clazz.newInstance()); } /** * Gets the CRC32 for the given string. * * @param input The string to get the CRC32 for. * @return The CRC32. */ public static String getCrc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(StandardCharsets.UTF_8)); return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase(); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param playbackClientSupplier Supplier for the playback client. * @return An HttpClient instance. */ public static HttpClient getHttpClient(Supplier<HttpClient> playbackClientSupplier) { if (ENVIRONMENT.getTestMode() != TestMode.PLAYBACK) { switch (ENVIRONMENT.getHttpClientType()) { case NETTY: return NETTY_HTTP_CLIENT; case OK_HTTP: return OK_HTTP_CLIENT; case VERTX: return VERTX_HTTP_CLIENT; case JDK_HTTP: return JDK_HTTP_HTTP_CLIENT; default: throw new IllegalArgumentException("Unknown http client type: " + ENVIRONMENT.getHttpClientType()); } } else { return playbackClientSupplier.get(); } } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream) { return convertInputStreamToByteArray(inputStream, 4096); } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @param expectedSize The expected size of the byte array. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream, int expectedSize) { byte[] buffer = new byte[4096]; int b; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedSize); try { while ((b = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, b); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return outputStream.toByteArray(); } /** * Compares two files for having equivalent content. * * @param file1 File used to upload data to the service * @param file2 File used to download data from the service * @param offset Write offset from the upload file * @param count Size of the download from the service * @return Whether the files have equivalent content based on offset and read count */ public static boolean compareFiles(File file1, File file2, long offset, long count) throws IOException { long pos = 0L; int defaultBufferSize = 128 * Constants.KB; FileInputStream stream1 = new FileInputStream(file1); stream1.skip(offset); FileInputStream stream2 = new FileInputStream(file2); try { int bufferSize = (int) Math.min(defaultBufferSize, count); while (pos < count) { int expectedReadCount = (int) Math.min(bufferSize, count - pos); byte[] buffer1 = new byte[expectedReadCount]; byte[] buffer2 = new byte[expectedReadCount]; int readCount1 = stream1.read(buffer1); int readCount2 = stream2.read(buffer2); TestUtils.assertArraysEqual(buffer1, buffer2); assertEquals(readCount1, readCount2); pos += expectedReadCount; } int verificationRead = stream2.read(); return pos == count && verificationRead == -1; } finally { stream1.close(); stream2.close(); } } /** * Instruments a builder with the test interceptor manager. * * @param builder The builder to instrument. * @param interceptorManager The interceptor manager to use. * @param <T> The type of the builder. * @param <E> The type of the service version. * @return The instrumented builder. */ @SuppressWarnings("unchecked") public static <T extends HttpTrait<T>, E extends Enum<E>> T instrument(T builder, HttpLogOptions logOptions, InterceptorManager interceptorManager) { builder.httpClient(getHttpClient(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (ENVIRONMENT.getServiceVersion() != null) { try { Method serviceVersionMethod = Arrays.stream(builder.getClass().getDeclaredMethods()) .filter(method -> "serviceVersion".equals(method.getName()) && method.getParameterCount() == 1 && ServiceVersion.class.isAssignableFrom(method.getParameterTypes()[0])) .findFirst() .orElseThrow(() -> new RuntimeException("Unable to find serviceVersion method for builder: " + builder.getClass())); Class<E> serviceVersionClass = (Class<E>) serviceVersionMethod.getParameterTypes()[0]; ServiceVersion serviceVersion = (ServiceVersion) Enum.valueOf(serviceVersionClass, ENVIRONMENT.getServiceVersion()); serviceVersionMethod.invoke(builder, serviceVersion); builder.addPolicy(new ServiceVersionValidationPolicy(serviceVersion.getVersion())); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } return builder.httpLogOptions(logOptions); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param interceptorManager The interceptor manager to use. * @return An HttpClient instance. */ public static HttpClient getHttpClient(InterceptorManager interceptorManager) { return StorageCommonTestUtils.getHttpClient(interceptorManager::getPlaybackClient); } /** * Gets a random byte array of the given size. * * @param size The size of the byte array. * @param testResourceNamer The test resource namer to use. * @return The random byte array. */ public static byte[] getRandomByteArray(int size, TestResourceNamer testResourceNamer) { long seed = UUID.fromString(testResourceNamer.randomUuid()).getMostSignificantBits() & Long.MAX_VALUE; Random rand = new Random(seed); byte[] data = new byte[size]; rand.nextBytes(data); return data; } /** * Gets a random ByteBuffer of the given size. * * @param size The size of the ByteBuffer. * @param testResourceNamer The test resource namer to use. * @return The random ByteBuffer. */ public static ByteBuffer getRandomData(int size, TestResourceNamer testResourceNamer) { return ByteBuffer.wrap(getRandomByteArray(size, testResourceNamer)); } /** * Gets a random file of the given size. * * @param size The size of the file. * @param testResourceNamer The test resource namer to use. * @return The random file. * @throws IOException If an I/O error occurs. */ public static File getRandomFile(int size, TestResourceNamer testResourceNamer) throws IOException { try { File file = File.createTempFile(CoreUtils.randomUuid().toString(), ".txt"); file.deleteOnExit(); if (size > Constants.MB) { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] data = getRandomByteArray(Constants.MB, testResourceNamer); int mbChunks = size / Constants.MB; int remaining = size % Constants.MB; for (int i = 0; i < mbChunks; i++) { fos.write(data); } if (remaining > 0) { fos.write(data, 0, remaining); } } } else { Files.write(file.toPath(), getRandomByteArray(size, testResourceNamer)); } return file; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Gets token credentials for a test. * * @param interceptorManager The interceptor manager to use. * @return The TokenCredential to use. */ }
`SYSTEM_ACCESSTOKEN` is not an Entra ID app secret, correct?
public static TokenCredential getTokenCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } else if (interceptorManager.isRecordMode()){ return new DefaultAzureCredentialBuilder().build(); } else { Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); builder.addLast(request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic())); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN");
public static TokenCredential getTokenCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } else if (interceptorManager.isRecordMode()){ return new DefaultAzureCredentialBuilder().build(); } else { Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); builder.addLast(request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic())); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
class StorageCommonTestUtils { public static final TestEnvironment ENVIRONMENT = TestEnvironment.getInstance(); private static final HttpClient NETTY_HTTP_CLIENT = new NettyAsyncHttpClientProvider().createInstance(); private static final HttpClient OK_HTTP_CLIENT = new OkHttpAsyncClientProvider().createInstance(); private static final HttpClient VERTX_HTTP_CLIENT = new VertxAsyncHttpClientProvider().createInstance(); private static final HttpClient JDK_HTTP_HTTP_CLIENT; static { HttpClient jdkHttpHttpClient; try { jdkHttpHttpClient = createJdkHttpClient(); } catch (LinkageError | ReflectiveOperationException e) { jdkHttpHttpClient = null; } JDK_HTTP_HTTP_CLIENT = jdkHttpHttpClient; } @SuppressWarnings("deprecation") private static HttpClient createJdkHttpClient() throws ReflectiveOperationException { Class<?> clazz = Class.forName("com.azure.core.http.jdk.httpclient.JdkHttpClientProvider"); return (HttpClient) clazz.getDeclaredMethod("createInstance").invoke(clazz.newInstance()); } /** * Gets the CRC32 for the given string. * * @param input The string to get the CRC32 for. * @return The CRC32. */ public static String getCrc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(StandardCharsets.UTF_8)); return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase(); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param playbackClientSupplier Supplier for the playback client. * @return An HttpClient instance. */ public static HttpClient getHttpClient(Supplier<HttpClient> playbackClientSupplier) { if (ENVIRONMENT.getTestMode() != TestMode.PLAYBACK) { switch (ENVIRONMENT.getHttpClientType()) { case NETTY: return NETTY_HTTP_CLIENT; case OK_HTTP: return OK_HTTP_CLIENT; case VERTX: return VERTX_HTTP_CLIENT; case JDK_HTTP: return JDK_HTTP_HTTP_CLIENT; default: throw new IllegalArgumentException("Unknown http client type: " + ENVIRONMENT.getHttpClientType()); } } else { return playbackClientSupplier.get(); } } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream) { return convertInputStreamToByteArray(inputStream, 4096); } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @param expectedSize The expected size of the byte array. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream, int expectedSize) { byte[] buffer = new byte[4096]; int b; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedSize); try { while ((b = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, b); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return outputStream.toByteArray(); } /** * Compares two files for having equivalent content. * * @param file1 File used to upload data to the service * @param file2 File used to download data from the service * @param offset Write offset from the upload file * @param count Size of the download from the service * @return Whether the files have equivalent content based on offset and read count */ public static boolean compareFiles(File file1, File file2, long offset, long count) throws IOException { long pos = 0L; int defaultBufferSize = 128 * Constants.KB; FileInputStream stream1 = new FileInputStream(file1); stream1.skip(offset); FileInputStream stream2 = new FileInputStream(file2); try { int bufferSize = (int) Math.min(defaultBufferSize, count); while (pos < count) { int expectedReadCount = (int) Math.min(bufferSize, count - pos); byte[] buffer1 = new byte[expectedReadCount]; byte[] buffer2 = new byte[expectedReadCount]; int readCount1 = stream1.read(buffer1); int readCount2 = stream2.read(buffer2); TestUtils.assertArraysEqual(buffer1, buffer2); assertEquals(readCount1, readCount2); pos += expectedReadCount; } int verificationRead = stream2.read(); return pos == count && verificationRead == -1; } finally { stream1.close(); stream2.close(); } } /** * Instruments a builder with the test interceptor manager. * * @param builder The builder to instrument. * @param interceptorManager The interceptor manager to use. * @param <T> The type of the builder. * @param <E> The type of the service version. * @return The instrumented builder. */ @SuppressWarnings("unchecked") public static <T extends HttpTrait<T>, E extends Enum<E>> T instrument(T builder, HttpLogOptions logOptions, InterceptorManager interceptorManager) { builder.httpClient(getHttpClient(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (ENVIRONMENT.getServiceVersion() != null) { try { Method serviceVersionMethod = Arrays.stream(builder.getClass().getDeclaredMethods()) .filter(method -> "serviceVersion".equals(method.getName()) && method.getParameterCount() == 1 && ServiceVersion.class.isAssignableFrom(method.getParameterTypes()[0])) .findFirst() .orElseThrow(() -> new RuntimeException("Unable to find serviceVersion method for builder: " + builder.getClass())); Class<E> serviceVersionClass = (Class<E>) serviceVersionMethod.getParameterTypes()[0]; ServiceVersion serviceVersion = (ServiceVersion) Enum.valueOf(serviceVersionClass, ENVIRONMENT.getServiceVersion()); serviceVersionMethod.invoke(builder, serviceVersion); builder.addPolicy(new ServiceVersionValidationPolicy(serviceVersion.getVersion())); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } return builder.httpLogOptions(logOptions); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param interceptorManager The interceptor manager to use. * @return An HttpClient instance. */ public static HttpClient getHttpClient(InterceptorManager interceptorManager) { return StorageCommonTestUtils.getHttpClient(interceptorManager::getPlaybackClient); } /** * Gets a random byte array of the given size. * * @param size The size of the byte array. * @param testResourceNamer The test resource namer to use. * @return The random byte array. */ public static byte[] getRandomByteArray(int size, TestResourceNamer testResourceNamer) { long seed = UUID.fromString(testResourceNamer.randomUuid()).getMostSignificantBits() & Long.MAX_VALUE; Random rand = new Random(seed); byte[] data = new byte[size]; rand.nextBytes(data); return data; } /** * Gets a random ByteBuffer of the given size. * * @param size The size of the ByteBuffer. * @param testResourceNamer The test resource namer to use. * @return The random ByteBuffer. */ public static ByteBuffer getRandomData(int size, TestResourceNamer testResourceNamer) { return ByteBuffer.wrap(getRandomByteArray(size, testResourceNamer)); } /** * Gets a random file of the given size. * * @param size The size of the file. * @param testResourceNamer The test resource namer to use. * @return The random file. * @throws IOException If an I/O error occurs. */ public static File getRandomFile(int size, TestResourceNamer testResourceNamer) throws IOException { try { File file = File.createTempFile(CoreUtils.randomUuid().toString(), ".txt"); file.deleteOnExit(); if (size > Constants.MB) { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] data = getRandomByteArray(Constants.MB, testResourceNamer); int mbChunks = size / Constants.MB; int remaining = size % Constants.MB; for (int i = 0; i < mbChunks; i++) { fos.write(data); } if (remaining > 0) { fos.write(data, 0, remaining); } } } else { Files.write(file.toPath(), getRandomByteArray(size, testResourceNamer)); } return file; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Gets token credentials for a test. * * @param interceptorManager The interceptor manager to use. * @return The TokenCredential to use. */ }
class StorageCommonTestUtils { public static final TestEnvironment ENVIRONMENT = TestEnvironment.getInstance(); private static final HttpClient NETTY_HTTP_CLIENT = new NettyAsyncHttpClientProvider().createInstance(); private static final HttpClient OK_HTTP_CLIENT = new OkHttpAsyncClientProvider().createInstance(); private static final HttpClient VERTX_HTTP_CLIENT = new VertxAsyncHttpClientProvider().createInstance(); private static final HttpClient JDK_HTTP_HTTP_CLIENT; static { HttpClient jdkHttpHttpClient; try { jdkHttpHttpClient = createJdkHttpClient(); } catch (LinkageError | ReflectiveOperationException e) { jdkHttpHttpClient = null; } JDK_HTTP_HTTP_CLIENT = jdkHttpHttpClient; } @SuppressWarnings("deprecation") private static HttpClient createJdkHttpClient() throws ReflectiveOperationException { Class<?> clazz = Class.forName("com.azure.core.http.jdk.httpclient.JdkHttpClientProvider"); return (HttpClient) clazz.getDeclaredMethod("createInstance").invoke(clazz.newInstance()); } /** * Gets the CRC32 for the given string. * * @param input The string to get the CRC32 for. * @return The CRC32. */ public static String getCrc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(StandardCharsets.UTF_8)); return String.format(Locale.US, "%08X", crc32.getValue()).toLowerCase(); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param playbackClientSupplier Supplier for the playback client. * @return An HttpClient instance. */ public static HttpClient getHttpClient(Supplier<HttpClient> playbackClientSupplier) { if (ENVIRONMENT.getTestMode() != TestMode.PLAYBACK) { switch (ENVIRONMENT.getHttpClientType()) { case NETTY: return NETTY_HTTP_CLIENT; case OK_HTTP: return OK_HTTP_CLIENT; case VERTX: return VERTX_HTTP_CLIENT; case JDK_HTTP: return JDK_HTTP_HTTP_CLIENT; default: throw new IllegalArgumentException("Unknown http client type: " + ENVIRONMENT.getHttpClientType()); } } else { return playbackClientSupplier.get(); } } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream) { return convertInputStreamToByteArray(inputStream, 4096); } /** * Converts an input stream to a byte array. * * @param inputStream The input stream to convert. * @param expectedSize The expected size of the byte array. * @return The byte array. */ public static byte[] convertInputStreamToByteArray(InputStream inputStream, int expectedSize) { byte[] buffer = new byte[4096]; int b; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedSize); try { while ((b = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, b); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return outputStream.toByteArray(); } /** * Compares two files for having equivalent content. * * @param file1 File used to upload data to the service * @param file2 File used to download data from the service * @param offset Write offset from the upload file * @param count Size of the download from the service * @return Whether the files have equivalent content based on offset and read count */ public static boolean compareFiles(File file1, File file2, long offset, long count) throws IOException { long pos = 0L; int defaultBufferSize = 128 * Constants.KB; FileInputStream stream1 = new FileInputStream(file1); stream1.skip(offset); FileInputStream stream2 = new FileInputStream(file2); try { int bufferSize = (int) Math.min(defaultBufferSize, count); while (pos < count) { int expectedReadCount = (int) Math.min(bufferSize, count - pos); byte[] buffer1 = new byte[expectedReadCount]; byte[] buffer2 = new byte[expectedReadCount]; int readCount1 = stream1.read(buffer1); int readCount2 = stream2.read(buffer2); TestUtils.assertArraysEqual(buffer1, buffer2); assertEquals(readCount1, readCount2); pos += expectedReadCount; } int verificationRead = stream2.read(); return pos == count && verificationRead == -1; } finally { stream1.close(); stream2.close(); } } /** * Instruments a builder with the test interceptor manager. * * @param builder The builder to instrument. * @param interceptorManager The interceptor manager to use. * @param <T> The type of the builder. * @param <E> The type of the service version. * @return The instrumented builder. */ @SuppressWarnings("unchecked") public static <T extends HttpTrait<T>, E extends Enum<E>> T instrument(T builder, HttpLogOptions logOptions, InterceptorManager interceptorManager) { builder.httpClient(getHttpClient(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } if (ENVIRONMENT.getServiceVersion() != null) { try { Method serviceVersionMethod = Arrays.stream(builder.getClass().getDeclaredMethods()) .filter(method -> "serviceVersion".equals(method.getName()) && method.getParameterCount() == 1 && ServiceVersion.class.isAssignableFrom(method.getParameterTypes()[0])) .findFirst() .orElseThrow(() -> new RuntimeException("Unable to find serviceVersion method for builder: " + builder.getClass())); Class<E> serviceVersionClass = (Class<E>) serviceVersionMethod.getParameterTypes()[0]; ServiceVersion serviceVersion = (ServiceVersion) Enum.valueOf(serviceVersionClass, ENVIRONMENT.getServiceVersion()); serviceVersionMethod.invoke(builder, serviceVersion); builder.addPolicy(new ServiceVersionValidationPolicy(serviceVersion.getVersion())); } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex); } } return builder.httpLogOptions(logOptions); } /** * Gets an HttpClient based on the test mode and the environment configuration. * * @param interceptorManager The interceptor manager to use. * @return An HttpClient instance. */ public static HttpClient getHttpClient(InterceptorManager interceptorManager) { return StorageCommonTestUtils.getHttpClient(interceptorManager::getPlaybackClient); } /** * Gets a random byte array of the given size. * * @param size The size of the byte array. * @param testResourceNamer The test resource namer to use. * @return The random byte array. */ public static byte[] getRandomByteArray(int size, TestResourceNamer testResourceNamer) { long seed = UUID.fromString(testResourceNamer.randomUuid()).getMostSignificantBits() & Long.MAX_VALUE; Random rand = new Random(seed); byte[] data = new byte[size]; rand.nextBytes(data); return data; } /** * Gets a random ByteBuffer of the given size. * * @param size The size of the ByteBuffer. * @param testResourceNamer The test resource namer to use. * @return The random ByteBuffer. */ public static ByteBuffer getRandomData(int size, TestResourceNamer testResourceNamer) { return ByteBuffer.wrap(getRandomByteArray(size, testResourceNamer)); } /** * Gets a random file of the given size. * * @param size The size of the file. * @param testResourceNamer The test resource namer to use. * @return The random file. * @throws IOException If an I/O error occurs. */ public static File getRandomFile(int size, TestResourceNamer testResourceNamer) throws IOException { try { File file = File.createTempFile(CoreUtils.randomUuid().toString(), ".txt"); file.deleteOnExit(); if (size > Constants.MB) { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] data = getRandomByteArray(Constants.MB, testResourceNamer); int mbChunks = size / Constants.MB; int remaining = size % Constants.MB; for (int i = 0; i < mbChunks; i++) { fos.write(data); } if (remaining > 0) { fos.write(data, 0, remaining); } } } else { Files.write(file.toPath(), getRandomByteArray(size, testResourceNamer)); } return file; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Gets token credentials for a test. * * @param interceptorManager The interceptor manager to use. * @return The TokenCredential to use. */ }
this breaks the proxy flow I think (backward compat), the Pipeline adapter in current flow is only configured if either httpClient is not null or proxy options are not configured. With this change, the pipeline adapter will get configured if httpClient is null and proxy options are configured.
void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient == null ? HttpClient.createDefault() : httpClient); httpPipelineAdapter = new HttpPipelineAdapter(this.httpPipeline, options); } }
this.httpPipeline = setupPipeline(httpClient == null ? HttpClient.createDefault() : httpClient);
void initializeHttpPipelineAdapter() { if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(getPipeline(), options); } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; IClientCredential credential; initializeHttpPipelineAdapter(); 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(this.httpPipeline)); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } HttpPipeline getPipeline() { if (this.httpPipeline != null) { return httpPipeline; } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; return this.httpPipeline; } HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient != null ? httpClient : HttpClient.createDefault()); return this.httpPipeline; } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
This call will break with this change. With proxy options (backward compat), this flow is currently invoked. https://github.com/Azure/azure-sdk-for-java/pull/40722/files#diff-b5937fc0e636a1c6954f1b77ed7149066d1f7048dd85d8db025609d2615c514cR277 To retain this, I'd say, we move this logic up, and before setting client Assertion credentials, check if pipeline is null then create the pipeline there for the function to consume.
void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient == null ? HttpClient.createDefault() : httpClient); httpPipelineAdapter = new HttpPipelineAdapter(this.httpPipeline, options); } }
this.httpPipeline = setupPipeline(httpClient == null ? HttpClient.createDefault() : httpClient);
void initializeHttpPipelineAdapter() { if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(getPipeline(), options); } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; IClientCredential credential; initializeHttpPipelineAdapter(); 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(this.httpPipeline)); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } HttpPipeline getPipeline() { if (this.httpPipeline != null) { return httpPipeline; } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; return this.httpPipeline; } HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient != null ? httpClient : HttpClient.createDefault()); return this.httpPipeline; } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
good catch, fixing!
void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient == null ? HttpClient.createDefault() : httpClient); httpPipelineAdapter = new HttpPipelineAdapter(this.httpPipeline, options); } }
this.httpPipeline = setupPipeline(httpClient == null ? HttpClient.createDefault() : httpClient);
void initializeHttpPipelineAdapter() { if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(getPipeline(), options); } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; IClientCredential credential; initializeHttpPipelineAdapter(); 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(this.httpPipeline)); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } applicationBuilder.sendX5c(options.isIncludeX5c()); 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(options.getRetryPolicy(), options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } HttpPipeline getPipeline() { if (this.httpPipeline != null) { return httpPipeline; } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; return this.httpPipeline; } HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient != null ? httpClient : HttpClient.createDefault()); return this.httpPipeline; } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
We should use different auth for different test modes. See this issue for more guidance on auth for testing - https://github.com/Azure/azure-sdk-for-java-pr/issues/1418
protected static WebPubSubClientBuilder getClientBuilder(String userId) { WebPubSubServiceClient client = new WebPubSubServiceClientBuilder() .endpoint(Configuration.getGlobalConfiguration().get( "WEB_PUB_SUB_ENDPOINT", "http: .credential(new DefaultAzureCredentialBuilder().build()) .hub("hub1") .buildClient(); return new WebPubSubClientBuilder().credential(new WebPubSubClientCredential(() -> client.getClientAccessToken( new GetClientAccessTokenOptions().setUserId(userId) .addRole("webpubsub.joinLeaveGroup") .addRole("webpubsub.sendToGroup")).getUrl())); }
.credential(new DefaultAzureCredentialBuilder().build())
protected static WebPubSubClientBuilder getClientBuilder(String userId) { WebPubSubServiceClient client = new WebPubSubServiceClientBuilder() .endpoint(Configuration.getGlobalConfiguration().get( "WEB_PUB_SUB_ENDPOINT")) .credential(new AzurePowerShellCredentialBuilder().build()) .hub("hub1") .buildClient(); return new WebPubSubClientBuilder().credential(new WebPubSubClientCredential(() -> client.getClientAccessToken( new GetClientAccessTokenOptions().setUserId(userId) .addRole("webpubsub.joinLeaveGroup") .addRole("webpubsub.sendToGroup")).getUrl())); }
class TestBase extends com.azure.core.test.TestBase { protected static WebPubSubClientBuilder getClientBuilder() { return getClientBuilder("user1"); } protected static WebPubSubClient getClient() { return getClientBuilder().buildClient(); } protected static void disconnect(WebPubSubClient client, boolean invalidPayload) { if (invalidPayload) { client.getWebsocketSession().sendTextAsync("invalid", result -> { }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { client.getWebsocketSession().closeSocket(); } try { int maxCount = 100; for (int i = 0; i < maxCount; ++i) { Thread.sleep(100); WebPubSubClientState state = client.getClientState(); if (state == WebPubSubClientState.CONNECTED) { break; } } } catch (InterruptedException e) { throw new RuntimeException(e); } Assertions.assertEquals(WebPubSubClientState.CONNECTED, client.getClientState()); } }
class TestBase extends com.azure.core.test.TestBase { protected static WebPubSubClientBuilder getClientBuilder() { return getClientBuilder("user1"); } protected static WebPubSubClient getClient() { return getClientBuilder().buildClient(); } protected static void disconnect(WebPubSubClient client, boolean invalidPayload) { if (invalidPayload) { client.getWebsocketSession().sendTextAsync("invalid", result -> { }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { client.getWebsocketSession().closeSocket(); } try { int maxCount = 100; for (int i = 0; i < maxCount; ++i) { Thread.sleep(100); WebPubSubClientState state = client.getClientState(); if (state == WebPubSubClientState.CONNECTED) { break; } } } catch (InterruptedException e) { throw new RuntimeException(e); } Assertions.assertEquals(WebPubSubClientState.CONNECTED, client.getClientState()); } }
There is only LIVE test for this lib (+ some UT with mocked client). I assume there is no recording of websocket traffic from test-proxy. The auth here is for azure-resourcemanager-webpubsub to get the credential for this lib -- 1 API call as prepare client. https://github.com/Azure/azure-sdk-for-java/blob/e582af833572a3367f19ff0bafb2a209f68774bf/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/TestBase.java#L37-L40
protected static WebPubSubClientBuilder getClientBuilder(String userId) { WebPubSubServiceClient client = new WebPubSubServiceClientBuilder() .endpoint(Configuration.getGlobalConfiguration().get( "WEB_PUB_SUB_ENDPOINT", "http: .credential(new DefaultAzureCredentialBuilder().build()) .hub("hub1") .buildClient(); return new WebPubSubClientBuilder().credential(new WebPubSubClientCredential(() -> client.getClientAccessToken( new GetClientAccessTokenOptions().setUserId(userId) .addRole("webpubsub.joinLeaveGroup") .addRole("webpubsub.sendToGroup")).getUrl())); }
.credential(new DefaultAzureCredentialBuilder().build())
protected static WebPubSubClientBuilder getClientBuilder(String userId) { WebPubSubServiceClient client = new WebPubSubServiceClientBuilder() .endpoint(Configuration.getGlobalConfiguration().get( "WEB_PUB_SUB_ENDPOINT")) .credential(new AzurePowerShellCredentialBuilder().build()) .hub("hub1") .buildClient(); return new WebPubSubClientBuilder().credential(new WebPubSubClientCredential(() -> client.getClientAccessToken( new GetClientAccessTokenOptions().setUserId(userId) .addRole("webpubsub.joinLeaveGroup") .addRole("webpubsub.sendToGroup")).getUrl())); }
class TestBase extends com.azure.core.test.TestBase { protected static WebPubSubClientBuilder getClientBuilder() { return getClientBuilder("user1"); } protected static WebPubSubClient getClient() { return getClientBuilder().buildClient(); } protected static void disconnect(WebPubSubClient client, boolean invalidPayload) { if (invalidPayload) { client.getWebsocketSession().sendTextAsync("invalid", result -> { }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { client.getWebsocketSession().closeSocket(); } try { int maxCount = 100; for (int i = 0; i < maxCount; ++i) { Thread.sleep(100); WebPubSubClientState state = client.getClientState(); if (state == WebPubSubClientState.CONNECTED) { break; } } } catch (InterruptedException e) { throw new RuntimeException(e); } Assertions.assertEquals(WebPubSubClientState.CONNECTED, client.getClientState()); } }
class TestBase extends com.azure.core.test.TestBase { protected static WebPubSubClientBuilder getClientBuilder() { return getClientBuilder("user1"); } protected static WebPubSubClient getClient() { return getClientBuilder().buildClient(); } protected static void disconnect(WebPubSubClient client, boolean invalidPayload) { if (invalidPayload) { client.getWebsocketSession().sendTextAsync("invalid", result -> { }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { client.getWebsocketSession().closeSocket(); } try { int maxCount = 100; for (int i = 0; i < maxCount; ++i) { Thread.sleep(100); WebPubSubClientState state = client.getClientState(); if (state == WebPubSubClientState.CONNECTED) { break; } } } catch (InterruptedException e) { throw new RuntimeException(e); } Assertions.assertEquals(WebPubSubClientState.CONNECTED, client.getClientState()); } }
I've switched to `AzurePowerShellCredentialBuilder`
protected static WebPubSubClientBuilder getClientBuilder(String userId) { WebPubSubServiceClient client = new WebPubSubServiceClientBuilder() .endpoint(Configuration.getGlobalConfiguration().get( "WEB_PUB_SUB_ENDPOINT", "http: .credential(new DefaultAzureCredentialBuilder().build()) .hub("hub1") .buildClient(); return new WebPubSubClientBuilder().credential(new WebPubSubClientCredential(() -> client.getClientAccessToken( new GetClientAccessTokenOptions().setUserId(userId) .addRole("webpubsub.joinLeaveGroup") .addRole("webpubsub.sendToGroup")).getUrl())); }
.credential(new DefaultAzureCredentialBuilder().build())
protected static WebPubSubClientBuilder getClientBuilder(String userId) { WebPubSubServiceClient client = new WebPubSubServiceClientBuilder() .endpoint(Configuration.getGlobalConfiguration().get( "WEB_PUB_SUB_ENDPOINT")) .credential(new AzurePowerShellCredentialBuilder().build()) .hub("hub1") .buildClient(); return new WebPubSubClientBuilder().credential(new WebPubSubClientCredential(() -> client.getClientAccessToken( new GetClientAccessTokenOptions().setUserId(userId) .addRole("webpubsub.joinLeaveGroup") .addRole("webpubsub.sendToGroup")).getUrl())); }
class TestBase extends com.azure.core.test.TestBase { protected static WebPubSubClientBuilder getClientBuilder() { return getClientBuilder("user1"); } protected static WebPubSubClient getClient() { return getClientBuilder().buildClient(); } protected static void disconnect(WebPubSubClient client, boolean invalidPayload) { if (invalidPayload) { client.getWebsocketSession().sendTextAsync("invalid", result -> { }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { client.getWebsocketSession().closeSocket(); } try { int maxCount = 100; for (int i = 0; i < maxCount; ++i) { Thread.sleep(100); WebPubSubClientState state = client.getClientState(); if (state == WebPubSubClientState.CONNECTED) { break; } } } catch (InterruptedException e) { throw new RuntimeException(e); } Assertions.assertEquals(WebPubSubClientState.CONNECTED, client.getClientState()); } }
class TestBase extends com.azure.core.test.TestBase { protected static WebPubSubClientBuilder getClientBuilder() { return getClientBuilder("user1"); } protected static WebPubSubClient getClient() { return getClientBuilder().buildClient(); } protected static void disconnect(WebPubSubClient client, boolean invalidPayload) { if (invalidPayload) { client.getWebsocketSession().sendTextAsync("invalid", result -> { }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { client.getWebsocketSession().closeSocket(); } try { int maxCount = 100; for (int i = 0; i < maxCount; ++i) { Thread.sleep(100); WebPubSubClientState state = client.getClientState(); if (state == WebPubSubClientState.CONNECTED) { break; } } } catch (InterruptedException e) { throw new RuntimeException(e); } Assertions.assertEquals(WebPubSubClientState.CONNECTED, client.getClientState()); } }
ClientEndpointType seems not committed to PR?
public Mono<WebPubSubClientAccessToken> getClientAccessToken(GetClientAccessTokenOptions options) { final ClientEndpointType clientEndpointType = options.getClientEndpointType(); final String path = clientEndpointType.equals(ClientEndpointType.MQTT) ? "clients/mqtt/hubs/" : "client/hubs/"; if (this.keyCredential == null) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, configureClientAccessTokenRequestOptions(options)) .map(response -> { String token = WebPubSubUtil.getToken(response.getValue()); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); } return Mono.fromCallable(() -> { final String audience = endpoint + (endpoint.endsWith("/") ? "" : "/") + path + hub; final String token = WebPubSubAuthenticationPolicy.getAuthenticationToken(audience, options, keyCredential); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); }
final String path = clientEndpointType.equals(ClientEndpointType.MQTT)
public Mono<WebPubSubClientAccessToken> getClientAccessToken(GetClientAccessTokenOptions options) { final ClientEndpointType clientEndpointType = options.getClientEndpointType(); final String path = clientEndpointType.equals(ClientEndpointType.MQTT) ? "clients/mqtt/hubs/" : "client/hubs/"; if (this.keyCredential == null) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, configureClientAccessTokenRequestOptions(options)) .map(response -> { String token = WebPubSubUtil.getToken(response.getValue()); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); } return Mono.fromCallable(() -> { final String audience = endpoint + (endpoint.endsWith("/") ? "" : "/") + path + hub; final String token = WebPubSubAuthenticationPolicy.getAuthenticationToken(audience, options, keyCredential); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); }
class WebPubSubServiceAsyncClient { private final WebPubSubsImpl serviceClient; private final String hub; private final String endpoint; private final AzureKeyCredential keyCredential; /** * Initializes an instance of WebPubSubs client. * * @param serviceClient the service client implementation. */ WebPubSubServiceAsyncClient(WebPubSubsImpl serviceClient, String hub, final String endpoint, final AzureKeyCredential keyCredential) { this.serviceClient = serviceClient; this.hub = hub; this.endpoint = endpoint; this.keyCredential = keyCredential; } /** * Creates a client access token. * * @param options Options to apply when creating the client access token. * @return A new client access token instance. */ @ServiceMethod(returns = ReturnType.SINGLE) static RequestOptions configureClientAccessTokenRequestOptions(GetClientAccessTokenOptions options) { RequestOptions requestOptions = new RequestOptions(); if (options.getUserId() != null) { requestOptions.addQueryParam("userId", options.getUserId()); } if (options.getExpiresAfter() != null) { requestOptions.addQueryParam("minutesToExpire", String.valueOf(options.getExpiresAfter().toMinutes())); } if (!CoreUtils.isNullOrEmpty(options.getRoles())) { options.getRoles().stream().forEach(roleName -> requestOptions.addQueryParam("role", roleName)); } if (!CoreUtils.isNullOrEmpty(options.getGroups())) { options.getGroups().stream().forEach(groupName -> requestOptions.addQueryParam("group", groupName)); } if (options.getClientEndpointType() != null) { requestOptions.addQueryParam("clientType", options.getClientEndpointType().toString()); } return requestOptions; } /** * Generate token for the client to connect Azure Web PubSub service. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>userId</td><td>String</td><td>No</td><td>User Id.</td></tr> * <tr><td>role</td><td>String</td><td>No</td><td>Roles that the connection with the generated token will have.</td></tr> * <tr><td>minutesToExpire</td><td>String</td><td>No</td><td>The expire time of the generated token.</td></tr> * <tr><td>group</td><td>Iterable&lt;String&gt;</td><td>No</td><td>Groups that the connection will join when it connects. Call {@link RequestOptions * </table> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * token: String * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the response. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ Mono<Response<BinaryData>> generateClientTokenWithResponse(RequestOptions requestOptions) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToAll(String message, WebPubSubContentType contentType) { return sendToAllWithResponse(BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if the connection with the given connectionId exists. * * @param connectionId The connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> connectionExistsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.connectionExistsWithResponseAsync(hub, connectionId, requestOptions); } /** * Close the client connection. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeConnectionWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.closeConnectionWithResponseAsync(hub, connectionId, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToConnection(String connectionId, String message, WebPubSubContentType contentType) { return this.sendToConnectionWithResponse(connectionId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if there are any client connections inside the given group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> groupExistsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.groupExistsWithResponseAsync(hub, group, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToGroup(String group, String message, WebPubSubContentType contentType) { return sendToGroupWithResponse(group, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a connection to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionToGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.addConnectionToGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Add filtered connections to multiple groups. * <p><strong>Request Body Schema</strong></p> * * <pre>{@code * { * groups: Iterable<String> (Optional) * filter: String (Optional) * } * }</pre> * * @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric * characters or underscore. * @param groupsToAdd Target groups and connection filter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionsToGroupsWithResponse(String hub, BinaryData groupsToAdd, RequestOptions requestOptions) { return this.serviceClient.addConnectionsToGroupsWithResponseAsync(hub, groupsToAdd, requestOptions); } /** * Remove a connection from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Remove a connection from all groups. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the {@link Response} on successful completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromAllGroupsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromAllGroupsWithResponseAsync(hub, connectionId, requestOptions); } /** * Check if there are any client connections connected for the given user. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> userExistsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.userExistsWithResponseAsync(hub, userId, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToUser(String userId, String message, WebPubSubContentType contentType) { return sendToUserWithResponse(userId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a user to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addUserToGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.addUserToGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from all groups. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromAllGroupsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromAllGroupsWithResponseAsync(hub, userId, requestOptions); } /** * Grant permission to the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> grantPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.grantPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Revoke permission for the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> revokePermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.revokePermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Check if a connection has permission to the specified action. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> checkPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.checkPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Close the connections in the hub. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeAllConnectionsWithResponse(RequestOptions requestOptions) { return this.serviceClient.closeAllConnectionsWithResponseAsync(hub, requestOptions); } /** * Close connections in the specific group. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the group.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeGroupConnectionsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.closeGroupConnectionsWithResponseAsync(hub, group, requestOptions); } /** * Close connections for the specific user. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections for the user.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param userId The user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeUserConnectionsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.closeUserConnectionsWithResponseAsync(hub, userId, requestOptions); } }
class WebPubSubServiceAsyncClient { private final WebPubSubsImpl serviceClient; private final String hub; private final String endpoint; private final AzureKeyCredential keyCredential; /** * Initializes an instance of WebPubSubs client. * * @param serviceClient the service client implementation. */ WebPubSubServiceAsyncClient(WebPubSubsImpl serviceClient, String hub, final String endpoint, final AzureKeyCredential keyCredential) { this.serviceClient = serviceClient; this.hub = hub; this.endpoint = endpoint; this.keyCredential = keyCredential; } /** * Creates a client access token. * * @param options Options to apply when creating the client access token. * @return A new client access token instance. */ @ServiceMethod(returns = ReturnType.SINGLE) static RequestOptions configureClientAccessTokenRequestOptions(GetClientAccessTokenOptions options) { RequestOptions requestOptions = new RequestOptions(); if (options.getUserId() != null) { requestOptions.addQueryParam("userId", options.getUserId()); } if (options.getExpiresAfter() != null) { requestOptions.addQueryParam("minutesToExpire", String.valueOf(options.getExpiresAfter().toMinutes())); } if (!CoreUtils.isNullOrEmpty(options.getRoles())) { options.getRoles().stream().forEach(roleName -> requestOptions.addQueryParam("role", roleName)); } if (!CoreUtils.isNullOrEmpty(options.getGroups())) { options.getGroups().stream().forEach(groupName -> requestOptions.addQueryParam("group", groupName)); } if (options.getClientEndpointType() != null) { requestOptions.addQueryParam("clientType", options.getClientEndpointType().toString()); } return requestOptions; } /** * Generate token for the client to connect Azure Web PubSub service. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>userId</td><td>String</td><td>No</td><td>User Id.</td></tr> * <tr><td>role</td><td>String</td><td>No</td><td>Roles that the connection with the generated token will have.</td></tr> * <tr><td>minutesToExpire</td><td>String</td><td>No</td><td>The expire time of the generated token.</td></tr> * <tr><td>group</td><td>Iterable&lt;String&gt;</td><td>No</td><td>Groups that the connection will join when it connects. Call {@link RequestOptions * </table> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * token: String * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the response. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ Mono<Response<BinaryData>> generateClientTokenWithResponse(RequestOptions requestOptions) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToAll(String message, WebPubSubContentType contentType) { return sendToAllWithResponse(BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if the connection with the given connectionId exists. * * @param connectionId The connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> connectionExistsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.connectionExistsWithResponseAsync(hub, connectionId, requestOptions); } /** * Close the client connection. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeConnectionWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.closeConnectionWithResponseAsync(hub, connectionId, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToConnection(String connectionId, String message, WebPubSubContentType contentType) { return this.sendToConnectionWithResponse(connectionId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if there are any client connections inside the given group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> groupExistsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.groupExistsWithResponseAsync(hub, group, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToGroup(String group, String message, WebPubSubContentType contentType) { return sendToGroupWithResponse(group, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a connection to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionToGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.addConnectionToGroupWithResponseAsync(hub, group, connectionId, requestOptions); } private Mono<Response<Void>> addConnectionsToGroupsWithResponse(String hub, BinaryData groupsToAdd, RequestOptions requestOptions) { return this.serviceClient.addConnectionsToGroupsWithResponseAsync(hub, groupsToAdd, requestOptions); } /** * Add filtered connections to multiple groups. * <p><strong>Request Body Schema</strong></p> * * <pre>{@code * { * groups: Iterable<String> (Optional) * filter: String (Optional) * } * }</pre> * * @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric * characters or underscore. * @param groups Target group names. Rejected by server on status code 400 if this parameter is null. * @param filter The filter to apply to the connections. * @return the completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addConnectionsToGroups(String hub, List<String> groups, String filter) { AddToGroupsRequest requestBody = new AddToGroupsRequest(); requestBody.setGroups(groups); requestBody.setFilter(filter); BinaryData body = BinaryData.fromObject(requestBody); return addConnectionsToGroupsWithResponse(hub, body, new RequestOptions()).flatMap(FluxUtil::toMono); } /** * Remove a connection from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Remove a connection from all groups. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the {@link Response} on successful completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromAllGroupsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromAllGroupsWithResponseAsync(hub, connectionId, requestOptions); } /** * Check if there are any client connections connected for the given user. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> userExistsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.userExistsWithResponseAsync(hub, userId, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToUser(String userId, String message, WebPubSubContentType contentType) { return sendToUserWithResponse(userId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a user to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addUserToGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.addUserToGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from all groups. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromAllGroupsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromAllGroupsWithResponseAsync(hub, userId, requestOptions); } /** * Grant permission to the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> grantPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.grantPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Revoke permission for the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> revokePermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.revokePermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Check if a connection has permission to the specified action. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> checkPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.checkPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Close the connections in the hub. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeAllConnectionsWithResponse(RequestOptions requestOptions) { return this.serviceClient.closeAllConnectionsWithResponseAsync(hub, requestOptions); } /** * Close connections in the specific group. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the group.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeGroupConnectionsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.closeGroupConnectionsWithResponseAsync(hub, group, requestOptions); } /** * Close connections for the specific user. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections for the user.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param userId The user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeUserConnectionsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.closeUserConnectionsWithResponseAsync(hub, userId, requestOptions); } }
Also I didn't see change to GetClientAccessTokenOptions.java
public Mono<WebPubSubClientAccessToken> getClientAccessToken(GetClientAccessTokenOptions options) { final ClientEndpointType clientEndpointType = options.getClientEndpointType(); final String path = clientEndpointType.equals(ClientEndpointType.MQTT) ? "clients/mqtt/hubs/" : "client/hubs/"; if (this.keyCredential == null) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, configureClientAccessTokenRequestOptions(options)) .map(response -> { String token = WebPubSubUtil.getToken(response.getValue()); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); } return Mono.fromCallable(() -> { final String audience = endpoint + (endpoint.endsWith("/") ? "" : "/") + path + hub; final String token = WebPubSubAuthenticationPolicy.getAuthenticationToken(audience, options, keyCredential); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); }
final String path = clientEndpointType.equals(ClientEndpointType.MQTT)
public Mono<WebPubSubClientAccessToken> getClientAccessToken(GetClientAccessTokenOptions options) { final ClientEndpointType clientEndpointType = options.getClientEndpointType(); final String path = clientEndpointType.equals(ClientEndpointType.MQTT) ? "clients/mqtt/hubs/" : "client/hubs/"; if (this.keyCredential == null) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, configureClientAccessTokenRequestOptions(options)) .map(response -> { String token = WebPubSubUtil.getToken(response.getValue()); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); } return Mono.fromCallable(() -> { final String audience = endpoint + (endpoint.endsWith("/") ? "" : "/") + path + hub; final String token = WebPubSubAuthenticationPolicy.getAuthenticationToken(audience, options, keyCredential); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); }
class WebPubSubServiceAsyncClient { private final WebPubSubsImpl serviceClient; private final String hub; private final String endpoint; private final AzureKeyCredential keyCredential; /** * Initializes an instance of WebPubSubs client. * * @param serviceClient the service client implementation. */ WebPubSubServiceAsyncClient(WebPubSubsImpl serviceClient, String hub, final String endpoint, final AzureKeyCredential keyCredential) { this.serviceClient = serviceClient; this.hub = hub; this.endpoint = endpoint; this.keyCredential = keyCredential; } /** * Creates a client access token. * * @param options Options to apply when creating the client access token. * @return A new client access token instance. */ @ServiceMethod(returns = ReturnType.SINGLE) static RequestOptions configureClientAccessTokenRequestOptions(GetClientAccessTokenOptions options) { RequestOptions requestOptions = new RequestOptions(); if (options.getUserId() != null) { requestOptions.addQueryParam("userId", options.getUserId()); } if (options.getExpiresAfter() != null) { requestOptions.addQueryParam("minutesToExpire", String.valueOf(options.getExpiresAfter().toMinutes())); } if (!CoreUtils.isNullOrEmpty(options.getRoles())) { options.getRoles().stream().forEach(roleName -> requestOptions.addQueryParam("role", roleName)); } if (!CoreUtils.isNullOrEmpty(options.getGroups())) { options.getGroups().stream().forEach(groupName -> requestOptions.addQueryParam("group", groupName)); } if (options.getClientEndpointType() != null) { requestOptions.addQueryParam("clientType", options.getClientEndpointType().toString()); } return requestOptions; } /** * Generate token for the client to connect Azure Web PubSub service. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>userId</td><td>String</td><td>No</td><td>User Id.</td></tr> * <tr><td>role</td><td>String</td><td>No</td><td>Roles that the connection with the generated token will have.</td></tr> * <tr><td>minutesToExpire</td><td>String</td><td>No</td><td>The expire time of the generated token.</td></tr> * <tr><td>group</td><td>Iterable&lt;String&gt;</td><td>No</td><td>Groups that the connection will join when it connects. Call {@link RequestOptions * </table> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * token: String * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the response. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ Mono<Response<BinaryData>> generateClientTokenWithResponse(RequestOptions requestOptions) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToAll(String message, WebPubSubContentType contentType) { return sendToAllWithResponse(BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if the connection with the given connectionId exists. * * @param connectionId The connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> connectionExistsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.connectionExistsWithResponseAsync(hub, connectionId, requestOptions); } /** * Close the client connection. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeConnectionWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.closeConnectionWithResponseAsync(hub, connectionId, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToConnection(String connectionId, String message, WebPubSubContentType contentType) { return this.sendToConnectionWithResponse(connectionId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if there are any client connections inside the given group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> groupExistsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.groupExistsWithResponseAsync(hub, group, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToGroup(String group, String message, WebPubSubContentType contentType) { return sendToGroupWithResponse(group, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a connection to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionToGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.addConnectionToGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Add filtered connections to multiple groups. * <p><strong>Request Body Schema</strong></p> * * <pre>{@code * { * groups: Iterable<String> (Optional) * filter: String (Optional) * } * }</pre> * * @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric * characters or underscore. * @param groupsToAdd Target groups and connection filter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionsToGroupsWithResponse(String hub, BinaryData groupsToAdd, RequestOptions requestOptions) { return this.serviceClient.addConnectionsToGroupsWithResponseAsync(hub, groupsToAdd, requestOptions); } /** * Remove a connection from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Remove a connection from all groups. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the {@link Response} on successful completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromAllGroupsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromAllGroupsWithResponseAsync(hub, connectionId, requestOptions); } /** * Check if there are any client connections connected for the given user. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> userExistsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.userExistsWithResponseAsync(hub, userId, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToUser(String userId, String message, WebPubSubContentType contentType) { return sendToUserWithResponse(userId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a user to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addUserToGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.addUserToGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from all groups. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromAllGroupsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromAllGroupsWithResponseAsync(hub, userId, requestOptions); } /** * Grant permission to the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> grantPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.grantPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Revoke permission for the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> revokePermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.revokePermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Check if a connection has permission to the specified action. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> checkPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.checkPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Close the connections in the hub. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeAllConnectionsWithResponse(RequestOptions requestOptions) { return this.serviceClient.closeAllConnectionsWithResponseAsync(hub, requestOptions); } /** * Close connections in the specific group. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the group.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeGroupConnectionsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.closeGroupConnectionsWithResponseAsync(hub, group, requestOptions); } /** * Close connections for the specific user. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections for the user.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param userId The user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeUserConnectionsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.closeUserConnectionsWithResponseAsync(hub, userId, requestOptions); } }
class WebPubSubServiceAsyncClient { private final WebPubSubsImpl serviceClient; private final String hub; private final String endpoint; private final AzureKeyCredential keyCredential; /** * Initializes an instance of WebPubSubs client. * * @param serviceClient the service client implementation. */ WebPubSubServiceAsyncClient(WebPubSubsImpl serviceClient, String hub, final String endpoint, final AzureKeyCredential keyCredential) { this.serviceClient = serviceClient; this.hub = hub; this.endpoint = endpoint; this.keyCredential = keyCredential; } /** * Creates a client access token. * * @param options Options to apply when creating the client access token. * @return A new client access token instance. */ @ServiceMethod(returns = ReturnType.SINGLE) static RequestOptions configureClientAccessTokenRequestOptions(GetClientAccessTokenOptions options) { RequestOptions requestOptions = new RequestOptions(); if (options.getUserId() != null) { requestOptions.addQueryParam("userId", options.getUserId()); } if (options.getExpiresAfter() != null) { requestOptions.addQueryParam("minutesToExpire", String.valueOf(options.getExpiresAfter().toMinutes())); } if (!CoreUtils.isNullOrEmpty(options.getRoles())) { options.getRoles().stream().forEach(roleName -> requestOptions.addQueryParam("role", roleName)); } if (!CoreUtils.isNullOrEmpty(options.getGroups())) { options.getGroups().stream().forEach(groupName -> requestOptions.addQueryParam("group", groupName)); } if (options.getClientEndpointType() != null) { requestOptions.addQueryParam("clientType", options.getClientEndpointType().toString()); } return requestOptions; } /** * Generate token for the client to connect Azure Web PubSub service. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>userId</td><td>String</td><td>No</td><td>User Id.</td></tr> * <tr><td>role</td><td>String</td><td>No</td><td>Roles that the connection with the generated token will have.</td></tr> * <tr><td>minutesToExpire</td><td>String</td><td>No</td><td>The expire time of the generated token.</td></tr> * <tr><td>group</td><td>Iterable&lt;String&gt;</td><td>No</td><td>Groups that the connection will join when it connects. Call {@link RequestOptions * </table> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * token: String * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the response. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ Mono<Response<BinaryData>> generateClientTokenWithResponse(RequestOptions requestOptions) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToAll(String message, WebPubSubContentType contentType) { return sendToAllWithResponse(BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if the connection with the given connectionId exists. * * @param connectionId The connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> connectionExistsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.connectionExistsWithResponseAsync(hub, connectionId, requestOptions); } /** * Close the client connection. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeConnectionWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.closeConnectionWithResponseAsync(hub, connectionId, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToConnection(String connectionId, String message, WebPubSubContentType contentType) { return this.sendToConnectionWithResponse(connectionId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if there are any client connections inside the given group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> groupExistsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.groupExistsWithResponseAsync(hub, group, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToGroup(String group, String message, WebPubSubContentType contentType) { return sendToGroupWithResponse(group, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a connection to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionToGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.addConnectionToGroupWithResponseAsync(hub, group, connectionId, requestOptions); } private Mono<Response<Void>> addConnectionsToGroupsWithResponse(String hub, BinaryData groupsToAdd, RequestOptions requestOptions) { return this.serviceClient.addConnectionsToGroupsWithResponseAsync(hub, groupsToAdd, requestOptions); } /** * Add filtered connections to multiple groups. * <p><strong>Request Body Schema</strong></p> * * <pre>{@code * { * groups: Iterable<String> (Optional) * filter: String (Optional) * } * }</pre> * * @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric * characters or underscore. * @param groups Target group names. Rejected by server on status code 400 if this parameter is null. * @param filter The filter to apply to the connections. * @return the completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addConnectionsToGroups(String hub, List<String> groups, String filter) { AddToGroupsRequest requestBody = new AddToGroupsRequest(); requestBody.setGroups(groups); requestBody.setFilter(filter); BinaryData body = BinaryData.fromObject(requestBody); return addConnectionsToGroupsWithResponse(hub, body, new RequestOptions()).flatMap(FluxUtil::toMono); } /** * Remove a connection from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Remove a connection from all groups. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the {@link Response} on successful completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromAllGroupsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromAllGroupsWithResponseAsync(hub, connectionId, requestOptions); } /** * Check if there are any client connections connected for the given user. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> userExistsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.userExistsWithResponseAsync(hub, userId, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToUser(String userId, String message, WebPubSubContentType contentType) { return sendToUserWithResponse(userId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a user to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addUserToGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.addUserToGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from all groups. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromAllGroupsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromAllGroupsWithResponseAsync(hub, userId, requestOptions); } /** * Grant permission to the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> grantPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.grantPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Revoke permission for the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> revokePermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.revokePermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Check if a connection has permission to the specified action. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> checkPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.checkPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Close the connections in the hub. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeAllConnectionsWithResponse(RequestOptions requestOptions) { return this.serviceClient.closeAllConnectionsWithResponseAsync(hub, requestOptions); } /** * Close connections in the specific group. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the group.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeGroupConnectionsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.closeGroupConnectionsWithResponseAsync(hub, group, requestOptions); } /** * Close connections for the specific user. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections for the user.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param userId The user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeUserConnectionsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.closeUserConnectionsWithResponseAsync(hub, userId, requestOptions); } }
Oh I'm seeing both changes are included in the PR already. Can you double check? https://github.com/Azure/azure-sdk-for-java/pull/40784/files#diff-378f75168506064970a2cbfd5ad1647468e502cba50e29073a0e099db491ef7c https://github.com/Azure/azure-sdk-for-java/pull/40784/files#diff-4a2e7e8521c6c5d25ae24a7f3d8b78066f189dbd70d04c8e1344fc737f805c71
public Mono<WebPubSubClientAccessToken> getClientAccessToken(GetClientAccessTokenOptions options) { final ClientEndpointType clientEndpointType = options.getClientEndpointType(); final String path = clientEndpointType.equals(ClientEndpointType.MQTT) ? "clients/mqtt/hubs/" : "client/hubs/"; if (this.keyCredential == null) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, configureClientAccessTokenRequestOptions(options)) .map(response -> { String token = WebPubSubUtil.getToken(response.getValue()); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); } return Mono.fromCallable(() -> { final String audience = endpoint + (endpoint.endsWith("/") ? "" : "/") + path + hub; final String token = WebPubSubAuthenticationPolicy.getAuthenticationToken(audience, options, keyCredential); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); }
final String path = clientEndpointType.equals(ClientEndpointType.MQTT)
public Mono<WebPubSubClientAccessToken> getClientAccessToken(GetClientAccessTokenOptions options) { final ClientEndpointType clientEndpointType = options.getClientEndpointType(); final String path = clientEndpointType.equals(ClientEndpointType.MQTT) ? "clients/mqtt/hubs/" : "client/hubs/"; if (this.keyCredential == null) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, configureClientAccessTokenRequestOptions(options)) .map(response -> { String token = WebPubSubUtil.getToken(response.getValue()); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); } return Mono.fromCallable(() -> { final String audience = endpoint + (endpoint.endsWith("/") ? "" : "/") + path + hub; final String token = WebPubSubAuthenticationPolicy.getAuthenticationToken(audience, options, keyCredential); return WebPubSubUtil.createToken(token, endpoint, hub, path); }); }
class WebPubSubServiceAsyncClient { private final WebPubSubsImpl serviceClient; private final String hub; private final String endpoint; private final AzureKeyCredential keyCredential; /** * Initializes an instance of WebPubSubs client. * * @param serviceClient the service client implementation. */ WebPubSubServiceAsyncClient(WebPubSubsImpl serviceClient, String hub, final String endpoint, final AzureKeyCredential keyCredential) { this.serviceClient = serviceClient; this.hub = hub; this.endpoint = endpoint; this.keyCredential = keyCredential; } /** * Creates a client access token. * * @param options Options to apply when creating the client access token. * @return A new client access token instance. */ @ServiceMethod(returns = ReturnType.SINGLE) static RequestOptions configureClientAccessTokenRequestOptions(GetClientAccessTokenOptions options) { RequestOptions requestOptions = new RequestOptions(); if (options.getUserId() != null) { requestOptions.addQueryParam("userId", options.getUserId()); } if (options.getExpiresAfter() != null) { requestOptions.addQueryParam("minutesToExpire", String.valueOf(options.getExpiresAfter().toMinutes())); } if (!CoreUtils.isNullOrEmpty(options.getRoles())) { options.getRoles().stream().forEach(roleName -> requestOptions.addQueryParam("role", roleName)); } if (!CoreUtils.isNullOrEmpty(options.getGroups())) { options.getGroups().stream().forEach(groupName -> requestOptions.addQueryParam("group", groupName)); } if (options.getClientEndpointType() != null) { requestOptions.addQueryParam("clientType", options.getClientEndpointType().toString()); } return requestOptions; } /** * Generate token for the client to connect Azure Web PubSub service. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>userId</td><td>String</td><td>No</td><td>User Id.</td></tr> * <tr><td>role</td><td>String</td><td>No</td><td>Roles that the connection with the generated token will have.</td></tr> * <tr><td>minutesToExpire</td><td>String</td><td>No</td><td>The expire time of the generated token.</td></tr> * <tr><td>group</td><td>Iterable&lt;String&gt;</td><td>No</td><td>Groups that the connection will join when it connects. Call {@link RequestOptions * </table> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * token: String * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the response. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ Mono<Response<BinaryData>> generateClientTokenWithResponse(RequestOptions requestOptions) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToAll(String message, WebPubSubContentType contentType) { return sendToAllWithResponse(BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if the connection with the given connectionId exists. * * @param connectionId The connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> connectionExistsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.connectionExistsWithResponseAsync(hub, connectionId, requestOptions); } /** * Close the client connection. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeConnectionWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.closeConnectionWithResponseAsync(hub, connectionId, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToConnection(String connectionId, String message, WebPubSubContentType contentType) { return this.sendToConnectionWithResponse(connectionId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if there are any client connections inside the given group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> groupExistsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.groupExistsWithResponseAsync(hub, group, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToGroup(String group, String message, WebPubSubContentType contentType) { return sendToGroupWithResponse(group, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a connection to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionToGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.addConnectionToGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Add filtered connections to multiple groups. * <p><strong>Request Body Schema</strong></p> * * <pre>{@code * { * groups: Iterable<String> (Optional) * filter: String (Optional) * } * }</pre> * * @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric * characters or underscore. * @param groupsToAdd Target groups and connection filter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionsToGroupsWithResponse(String hub, BinaryData groupsToAdd, RequestOptions requestOptions) { return this.serviceClient.addConnectionsToGroupsWithResponseAsync(hub, groupsToAdd, requestOptions); } /** * Remove a connection from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Remove a connection from all groups. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the {@link Response} on successful completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromAllGroupsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromAllGroupsWithResponseAsync(hub, connectionId, requestOptions); } /** * Check if there are any client connections connected for the given user. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> userExistsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.userExistsWithResponseAsync(hub, userId, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToUser(String userId, String message, WebPubSubContentType contentType) { return sendToUserWithResponse(userId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a user to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addUserToGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.addUserToGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from all groups. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromAllGroupsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromAllGroupsWithResponseAsync(hub, userId, requestOptions); } /** * Grant permission to the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> grantPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.grantPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Revoke permission for the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> revokePermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.revokePermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Check if a connection has permission to the specified action. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> checkPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.checkPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Close the connections in the hub. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeAllConnectionsWithResponse(RequestOptions requestOptions) { return this.serviceClient.closeAllConnectionsWithResponseAsync(hub, requestOptions); } /** * Close connections in the specific group. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the group.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeGroupConnectionsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.closeGroupConnectionsWithResponseAsync(hub, group, requestOptions); } /** * Close connections for the specific user. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections for the user.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param userId The user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeUserConnectionsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.closeUserConnectionsWithResponseAsync(hub, userId, requestOptions); } }
class WebPubSubServiceAsyncClient { private final WebPubSubsImpl serviceClient; private final String hub; private final String endpoint; private final AzureKeyCredential keyCredential; /** * Initializes an instance of WebPubSubs client. * * @param serviceClient the service client implementation. */ WebPubSubServiceAsyncClient(WebPubSubsImpl serviceClient, String hub, final String endpoint, final AzureKeyCredential keyCredential) { this.serviceClient = serviceClient; this.hub = hub; this.endpoint = endpoint; this.keyCredential = keyCredential; } /** * Creates a client access token. * * @param options Options to apply when creating the client access token. * @return A new client access token instance. */ @ServiceMethod(returns = ReturnType.SINGLE) static RequestOptions configureClientAccessTokenRequestOptions(GetClientAccessTokenOptions options) { RequestOptions requestOptions = new RequestOptions(); if (options.getUserId() != null) { requestOptions.addQueryParam("userId", options.getUserId()); } if (options.getExpiresAfter() != null) { requestOptions.addQueryParam("minutesToExpire", String.valueOf(options.getExpiresAfter().toMinutes())); } if (!CoreUtils.isNullOrEmpty(options.getRoles())) { options.getRoles().stream().forEach(roleName -> requestOptions.addQueryParam("role", roleName)); } if (!CoreUtils.isNullOrEmpty(options.getGroups())) { options.getGroups().stream().forEach(groupName -> requestOptions.addQueryParam("group", groupName)); } if (options.getClientEndpointType() != null) { requestOptions.addQueryParam("clientType", options.getClientEndpointType().toString()); } return requestOptions; } /** * Generate token for the client to connect Azure Web PubSub service. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>userId</td><td>String</td><td>No</td><td>User Id.</td></tr> * <tr><td>role</td><td>String</td><td>No</td><td>Roles that the connection with the generated token will have.</td></tr> * <tr><td>minutesToExpire</td><td>String</td><td>No</td><td>The expire time of the generated token.</td></tr> * <tr><td>group</td><td>Iterable&lt;String&gt;</td><td>No</td><td>Groups that the connection will join when it connects. Call {@link RequestOptions * </table> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * token: String * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the response. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ Mono<Response<BinaryData>> generateClientTokenWithResponse(RequestOptions requestOptions) { return this.serviceClient.generateClientTokenWithResponseAsync(hub, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToAllWithResponse(BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToAllWithResponseAsync(hub, "", message, requestOptions); } /** * Broadcast content inside request body to all the connected client connections. * * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToAll(String message, WebPubSubContentType contentType) { return sendToAllWithResponse(BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if the connection with the given connectionId exists. * * @param connectionId The connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> connectionExistsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.connectionExistsWithResponseAsync(hub, connectionId, requestOptions); } /** * Close the client connection. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeConnectionWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.closeConnectionWithResponseAsync(hub, connectionId, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToConnectionWithResponse(String connectionId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToConnectionWithResponseAsync(hub, connectionId, "", message, requestOptions); } /** * Send content inside request body to the specific connection. * * @param connectionId The connection ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToConnection(String connectionId, String message, WebPubSubContentType contentType) { return this.sendToConnectionWithResponse(connectionId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Check if there are any client connections inside the given group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> groupExistsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.groupExistsWithResponseAsync(hub, group, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToGroupWithResponse(String group, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToGroupWithResponseAsync(hub, group, "", message, requestOptions); } /** * Send content inside request body to a group of connections. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToGroup(String group, String message, WebPubSubContentType contentType) { return sendToGroupWithResponse(group, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a connection to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addConnectionToGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.addConnectionToGroupWithResponseAsync(hub, group, connectionId, requestOptions); } private Mono<Response<Void>> addConnectionsToGroupsWithResponse(String hub, BinaryData groupsToAdd, RequestOptions requestOptions) { return this.serviceClient.addConnectionsToGroupsWithResponseAsync(hub, groupsToAdd, requestOptions); } /** * Add filtered connections to multiple groups. * <p><strong>Request Body Schema</strong></p> * * <pre>{@code * { * groups: Iterable<String> (Optional) * filter: String (Optional) * } * }</pre> * * @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric * characters or underscore. * @param groups Target group names. Rejected by server on status code 400 if this parameter is null. * @param filter The filter to apply to the connections. * @return the completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addConnectionsToGroups(String hub, List<String> groups, String filter) { AddToGroupsRequest requestBody = new AddToGroupsRequest(); requestBody.setGroups(groups); requestBody.setFilter(filter); BinaryData body = BinaryData.fromObject(requestBody); return addConnectionsToGroupsWithResponse(hub, body, new RequestOptions()).flatMap(FluxUtil::toMono); } /** * Remove a connection from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromGroupWithResponse(String group, String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromGroupWithResponseAsync(hub, group, connectionId, requestOptions); } /** * Remove a connection from all groups. * * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the {@link Response} on successful completion of {@link Mono}. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeConnectionFromAllGroupsWithResponse(String connectionId, RequestOptions requestOptions) { return this.serviceClient.removeConnectionFromAllGroupsWithResponseAsync(hub, connectionId, requestOptions); } /** * Check if there are any client connections connected for the given user. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> userExistsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.userExistsWithResponseAsync(hub, userId, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @param contentLength The contentLength parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, WebPubSubContentType contentType, long contentLength, RequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString()); requestOptions.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> sendToUserWithResponse(String userId, BinaryData message, RequestOptions requestOptions) { return this.serviceClient.sendToUserWithResponseAsync(hub, userId, "", message, requestOptions); } /** * Send content inside request body to the specific user. * * @param userId The user ID. * @param message The payload body. * @param contentType Upload file type. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> sendToUser(String userId, String message, WebPubSubContentType contentType) { return sendToUserWithResponse(userId, BinaryData.fromString(message), new RequestOptions().setHeader(HttpHeaderName.CONTENT_TYPE, contentType.toString())) .flatMap(FluxUtil::toMono); } /** * Add a user to the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addUserToGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.addUserToGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from the target group. * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromGroupWithResponse(String group, String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromGroupWithResponseAsync(hub, group, userId, requestOptions); } /** * Remove a user from all groups. * * @param userId Target user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeUserFromAllGroupsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.removeUserFromAllGroupsWithResponseAsync(hub, userId, requestOptions); } /** * Grant permission to the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> grantPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.grantPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Revoke permission for the connection. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> revokePermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.revokePermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Check if a connection has permission to the specified action. * * @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup. * @param connectionId Target connection ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return whether resource exists. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> checkPermissionWithResponse(WebPubSubPermission permission, String connectionId, RequestOptions requestOptions) { return this.serviceClient.checkPermissionWithResponseAsync(hub, permission.toString(), connectionId, requestOptions); } /** * Close the connections in the hub. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeAllConnectionsWithResponse(RequestOptions requestOptions) { return this.serviceClient.closeAllConnectionsWithResponseAsync(hub, requestOptions); } /** * Close connections in the specific group. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the group.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param group Target group name, which length should be greater than 0 and less than 1025. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeGroupConnectionsWithResponse(String group, RequestOptions requestOptions) { return this.serviceClient.closeGroupConnectionsWithResponseAsync(hub, group, requestOptions); } /** * Close connections for the specific user. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections for the user.</td></tr> * <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr> * <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr> * </table> * * @param userId The user ID. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @return the completion. * @throws HttpResponseException thrown if status code is 400 or above, if throwOnError in requestOptions is not * false. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> closeUserConnectionsWithResponse(String userId, RequestOptions requestOptions) { return this.serviceClient.closeUserConnectionsWithResponseAsync(hub, userId, requestOptions); } }
FYI: https://github.com/Azure/azure-sdk-for-java/pull/40406/files#r1637109223
TokenCredential tokenCredential() { return new AzurePowerShellCredentialBuilder().build(); }
return new AzurePowerShellCredentialBuilder().build();
TokenCredential tokenCredential() { return new AzurePowerShellCredentialBuilder().build(); }
class ApplicationConfiguration { @Bean(name = DEFAULT_TOKEN_CREDENTIAL_BEAN_NAME) }
class ApplicationConfiguration { @Bean(name = DEFAULT_TOKEN_CREDENTIAL_BEAN_NAME) }
Further out, should track adding synchronous APIs to Avro parsing. At a high-level this method feels odd as it is converting an `InputStream` to `Flux<ByteBuffer>` to process data to convert back to an `InputStream`.
public InputStream readInputStream(InputStream inputStream) throws IOException { Flux<ByteBuffer> avroFlux = toFluxByteBuffer(inputStream); Flux<ByteBuffer> processedData = new AvroReaderFactory().getAvroReader(avroFlux).read() .map(AvroObject::getObject) .concatMap(this::parseRecord); return new FluxInputStream(processedData); }
Flux<ByteBuffer> processedData = new AvroReaderFactory().getAvroReader(avroFlux).read()
public InputStream readInputStream(InputStream inputStream) throws IOException { AvroReaderSyncFactory avroReaderSyncFactory = new AvroReaderSyncFactory(); ByteBuffer fullBuffer = convertInputStreamToByteBuffer(inputStream); Iterable<AvroObject> avroObjects = avroReaderSyncFactory.getAvroReader(fullBuffer).read(); byte[] processedData = serializeAvroObjectsToBytes(avroObjects); return new ByteArrayInputStream(processedData); }
class BlobQueryReader { private final Flux<ByteBuffer> avro; private final Consumer<BlobQueryProgress> progressConsumer; private final Consumer<BlobQueryError> errorConsumer; /** * Creates a new BlobQueryReader. * * @param avro The reactive avro stream. * @param progressConsumer The progress consumer. * @param errorConsumer The error consumer. */ public BlobQueryReader(Flux<ByteBuffer> avro, Consumer<BlobQueryProgress> progressConsumer, Consumer<BlobQueryError> errorConsumer) { this.avro = avro; this.progressConsumer = progressConsumer; this.errorConsumer = errorConsumer; } /** * Avro parses a query reactive stream. * * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @return The parsed query reactive stream. */ public Flux<ByteBuffer> read() { return new AvroReaderFactory().getAvroReader(avro).read() .map(AvroObject::getObject) .concatMap(this::parseRecord); } /** * Avro parses a query reactive stream. * * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @return The parsed query reactive stream. */ private Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { return FluxUtil.toFluxByteBuffer(inputStream); } /** * Parses a query record. * * @param quickQueryRecord The query record. * @return The optional data in the record. */ private Mono<ByteBuffer> parseRecord(Object quickQueryRecord) { if (!(quickQueryRecord instanceof Map)) { return Mono.error(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> record = (Map<?, ?>) quickQueryRecord; Object recordSchema = record.get(AvroConstants.RECORD); switch (recordSchema.toString()) { case "resultData": return parseResultData(record); case "end": return parseEnd(record); case "progress": return parseProgress(record); case "error": return parseError(record); default: return Mono.error(new IllegalStateException(String.format("Unknown record type %s " + "while parsing query response. ", recordSchema.toString()))); } } /** * Parses a query result data record. * @param dataRecord The query result data record. * @return The data in the record. */ private Mono<ByteBuffer> parseResultData(Map<?, ?> dataRecord) { Object data = dataRecord.get("data"); if (checkParametersNotNull(data)) { AvroSchema.checkType("data", data, List.class); return Mono.just(ByteBuffer.wrap(AvroSchema.getBytes((List<?>) data))); } else { return Mono.error(new IllegalArgumentException("Failed to parse result data record from " + "query response stream.")); } } /** * Parses a query end record. * @param endRecord The query end record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseEnd(Map<?, ?> endRecord) { if (progressConsumer != null) { Object totalBytes = endRecord.get("totalBytes"); if (checkParametersNotNull(totalBytes)) { AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) totalBytes, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse end record from query " + "response stream.")); } } return Mono.empty(); } /** * Parses a query progress record. * @param progressRecord The query progress record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseProgress(Map<?, ?> progressRecord) { if (progressConsumer != null) { Object bytesScanned = progressRecord.get("bytesScanned"); Object totalBytes = progressRecord.get("totalBytes"); if (checkParametersNotNull(bytesScanned, totalBytes)) { AvroSchema.checkType("bytesScanned", bytesScanned, Long.class); AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) bytesScanned, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse progress record from " + "query response stream.")); } } return Mono.empty(); } /** * Parses a query error record. * @param errorRecord The query error record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseError(Map<?, ?> errorRecord) { Object fatal = errorRecord.get("fatal"); Object name = errorRecord.get("name"); Object description = errorRecord.get("description"); Object position = errorRecord.get("position"); if (checkParametersNotNull(fatal, name, description, position)) { AvroSchema.checkType("fatal", fatal, Boolean.class); AvroSchema.checkType("name", name, String.class); AvroSchema.checkType("description", description, String.class); AvroSchema.checkType("position", position, Long.class); BlobQueryError error = new BlobQueryError((Boolean) fatal, (String) name, (String) description, (Long) position); if (errorConsumer != null) { errorConsumer.accept(error); } else { return Mono.error(new IOException("An error was reported during query response processing, " + System.lineSeparator() + error.toString())); } } else { return Mono.error(new IllegalArgumentException("Failed to parse error record from " + "query response stream.")); } return Mono.empty(); } /** * Checks whether or not all parameters are non-null. */ private static boolean checkParametersNotNull(Object... data) { for (Object o : data) { if (o == null || o instanceof AvroNullSchema.Null) { return false; } } return true; } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformInputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryParquetSerialization) { generatedFormat.setType(QueryFormatType.PARQUET); generatedFormat.setParquetTextConfiguration(transformParquet( (BlobQueryParquetSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid input serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformOutputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryArrowSerialization) { generatedFormat.setType(QueryFormatType.ARROW); generatedFormat.setArrowConfiguration(transformArrow( (BlobQueryArrowSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid output serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a BlobQueryDelimitedSerialization into a DelimitedTextConfiguration. * * @param delimitedSerialization {@link BlobQueryDelimitedSerialization} * @return {@link DelimitedTextConfiguration} */ private static DelimitedTextConfiguration transformDelimited( BlobQueryDelimitedSerialization delimitedSerialization) { if (delimitedSerialization == null) { return null; } return new DelimitedTextConfiguration() .setColumnSeparator(charToString(delimitedSerialization.getColumnSeparator())) .setEscapeChar(charToString(delimitedSerialization.getEscapeChar())) .setFieldQuote(charToString(delimitedSerialization.getFieldQuote())) .setHeadersPresent(delimitedSerialization.isHeadersPresent()) .setRecordSeparator(charToString(delimitedSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryJsonSerialization into a JsonTextConfiguration. * * @param jsonSerialization {@link BlobQueryJsonSerialization} * @return {@link JsonTextConfiguration} */ private static JsonTextConfiguration transformJson(BlobQueryJsonSerialization jsonSerialization) { if (jsonSerialization == null) { return null; } return new JsonTextConfiguration() .setRecordSeparator(charToString(jsonSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryParquetSerialization into an Object. * * @param parquetSerialization {@link BlobQueryParquetSerialization} * @return {@link JsonTextConfiguration} */ private static Object transformParquet(BlobQueryParquetSerialization parquetSerialization) { /* This method returns an Object since the ParquetConfiguration currently accepts no options. This results in the generator generating ParquetConfiguration as an Object. */ if (parquetSerialization == null) { return null; } return new Object(); } /** * Transforms a BlobQueryArrowSerialization into a ArrowConfiguration. * * @param arrowSerialization {@link BlobQueryArrowSerialization} * @return {@link ArrowConfiguration} */ private static ArrowConfiguration transformArrow(BlobQueryArrowSerialization arrowSerialization) { if (arrowSerialization == null) { return null; } List<ArrowField> schema = arrowSerialization.getSchema() == null ? null : new ArrayList<>(arrowSerialization.getSchema().size()); if (schema != null) { for (BlobQueryArrowField field : arrowSerialization.getSchema()) { if (field == null) { schema.add(null); } else { schema.add(new ArrowField() .setName(field.getName()) .setPrecision(field.getPrecision()) .setScale(field.getScale()) .setType(field.getType().toString()) ); } } } return new ArrowConfiguration().setSchema(schema); } private static String charToString(char c) { return c == '\0' ? "" : Character.toString(c); } }
class BlobQueryReader { private static final ClientLogger LOGGER = new ClientLogger(BlobQueryReader.class); private final Flux<ByteBuffer> avro; private final Consumer<BlobQueryProgress> progressConsumer; private final Consumer<BlobQueryError> errorConsumer; /** * Creates a new BlobQueryReader. * * @param avro The reactive avro stream. * @param progressConsumer The progress consumer. * @param errorConsumer The error consumer. */ public BlobQueryReader(Flux<ByteBuffer> avro, Consumer<BlobQueryProgress> progressConsumer, Consumer<BlobQueryError> errorConsumer) { this.avro = avro; this.progressConsumer = progressConsumer; this.errorConsumer = errorConsumer; } /** * Avro parses a query reactive stream. * <p> * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @return The parsed query reactive stream. */ public Flux<ByteBuffer> read() { return new AvroReaderFactory().getAvroReader(avro).read() .map(AvroObject::getObject) .concatMap(this::parseRecord); } /** * Avro parses a query reactive stream. * * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @param inputStream The input stream to read from. * @return The parsed query reactive stream. * @throws IOException If an I/O error occurs. */ private ByteBuffer convertInputStreamToByteBuffer(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] data = outputStream.toByteArray(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length); byteBuffer.put(data); byteBuffer.flip(); return byteBuffer; } private byte[] serializeAvroObjectsToBytes(Iterable<AvroObject> avroObjects) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (AvroObject avroObject : avroObjects) { try { Object potentialMap = avroObject.getObject(); if (!(potentialMap instanceof Map)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> recordMap = (Map<?, ?>) potentialMap; ByteBuffer buffer = parseSyncRecord(recordMap); if (buffer != null) { if (buffer.hasArray()) { outputStream.write(buffer.array(), buffer.position(), buffer.remaining()); } else { byte[] data = new byte[buffer.remaining()]; buffer.get(data); outputStream.write(data); } buffer.clear(); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } return outputStream.toByteArray(); } /** * Parses a query record. * * @param quickQueryRecord The query record. * @return The optional data in the record. */ private Mono<ByteBuffer> parseRecord(Object quickQueryRecord) { if (!(quickQueryRecord instanceof Map)) { return Mono.error(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> record = (Map<?, ?>) quickQueryRecord; Object recordSchema = record.get(AvroConstants.RECORD); switch (recordSchema.toString()) { case "resultData": return parseResultData(record); case "end": return parseEnd(record); case "progress": return parseProgress(record); case "error": return parseError(record); default: return Mono.error(new IllegalStateException(String.format("Unknown record type %s " + "while parsing query response. ", recordSchema.toString()))); } } /** * Parses a query record. * * @param quickQueryRecord The query record. * @return The optional data in the record. */ private ByteBuffer parseSyncRecord(Object quickQueryRecord) { if (!(quickQueryRecord instanceof Map)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> record = (Map<?, ?>) quickQueryRecord; Object recordSchema = record.get(AvroConstants.RECORD); switch (recordSchema.toString()) { case "resultData": return parseSyncResultData(record); case "end": return parseSyncEnd(record); case "progress": return parseSyncProgress(record); case "error": return parseSyncError(record); default: throw LOGGER.logExceptionAsError(new IllegalStateException(String.format("Unknown record type %s " + "while parsing query response. ", recordSchema.toString()))); } } /** * Parses a query result data record. * @param dataRecord The query result data record. * @return The data in the record. */ private Mono<ByteBuffer> parseResultData(Map<?, ?> dataRecord) { Object data = dataRecord.get("data"); if (checkParametersNotNull(data)) { AvroSchema.checkType("data", data, List.class); return Mono.just(ByteBuffer.wrap(AvroSchema.getBytes((List<?>) data))); } else { return Mono.error(new IllegalArgumentException("Failed to parse result data record from " + "query response stream.")); } } /** * Parses a query result data record. * @param dataRecord The query result data record. * @return The data in the record. */ private ByteBuffer parseSyncResultData(Map<?, ?> dataRecord) { Object data = dataRecord.get("data"); if (checkParametersNotNull(data)) { AvroSchema.checkType("data", data, List.class); return ByteBuffer.wrap(AvroSchema.getBytes((List<?>) data)); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse result data record from " + "query response stream.")); } } /** * Parses a query end record. * @param endRecord The query end record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseEnd(Map<?, ?> endRecord) { if (progressConsumer != null) { Object totalBytes = endRecord.get("totalBytes"); if (checkParametersNotNull(totalBytes)) { AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) totalBytes, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse end record from query " + "response stream.")); } } return Mono.empty(); } /** * Parses a query end record. * @param endRecord The query end record. * @return Mono.empty or Mono.error */ private ByteBuffer parseSyncEnd(Map<?, ?> endRecord) { if (progressConsumer != null) { Object totalBytes = endRecord.get("totalBytes"); if (checkParametersNotNull(totalBytes)) { AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) totalBytes, (long) totalBytes)); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse end record from query " + "response stream.")); } } return null; } /** * Parses a query progress record. * @param progressRecord The query progress record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseProgress(Map<?, ?> progressRecord) { if (progressConsumer != null) { Object bytesScanned = progressRecord.get("bytesScanned"); Object totalBytes = progressRecord.get("totalBytes"); if (checkParametersNotNull(bytesScanned, totalBytes)) { AvroSchema.checkType("bytesScanned", bytesScanned, Long.class); AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) bytesScanned, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse progress record from " + "query response stream.")); } } return Mono.empty(); } /** * Parses a query progress record. * @param progressRecord The query progress record. * @return Mono.empty or Mono.error */ private ByteBuffer parseSyncProgress(Map<?, ?> progressRecord) { if (progressConsumer != null) { Object bytesScanned = progressRecord.get("bytesScanned"); Object totalBytes = progressRecord.get("totalBytes"); if (checkParametersNotNull(bytesScanned, totalBytes)) { AvroSchema.checkType("bytesScanned", bytesScanned, Long.class); AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) bytesScanned, (long) totalBytes)); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse progress record from " + "query response stream.")); } } return null; } /** * Parses a query error record. * @param errorRecord The query error record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseError(Map<?, ?> errorRecord) { Object fatal = errorRecord.get("fatal"); Object name = errorRecord.get("name"); Object description = errorRecord.get("description"); Object position = errorRecord.get("position"); if (checkParametersNotNull(fatal, name, description, position)) { AvroSchema.checkType("fatal", fatal, Boolean.class); AvroSchema.checkType("name", name, String.class); AvroSchema.checkType("description", description, String.class); AvroSchema.checkType("position", position, Long.class); BlobQueryError error = new BlobQueryError((Boolean) fatal, (String) name, (String) description, (Long) position); if (errorConsumer != null) { errorConsumer.accept(error); } else { return Mono.error(new IOException("An error was reported during query response processing, " + System.lineSeparator() + error.toString())); } } else { return Mono.error(new IllegalArgumentException("Failed to parse error record from " + "query response stream.")); } return Mono.empty(); } /** * Parses a query error record. * @param errorRecord The query error record. * @return Mono.empty or Mono.error */ private ByteBuffer parseSyncError(Map<?, ?> errorRecord) { Object fatal = errorRecord.get("fatal"); Object name = errorRecord.get("name"); Object description = errorRecord.get("description"); Object position = errorRecord.get("position"); if (checkParametersNotNull(fatal, name, description, position)) { AvroSchema.checkType("fatal", fatal, Boolean.class); AvroSchema.checkType("name", name, String.class); AvroSchema.checkType("description", description, String.class); AvroSchema.checkType("position", position, Long.class); BlobQueryError error = new BlobQueryError((Boolean) fatal, (String) name, (String) description, (Long) position); if (errorConsumer != null) { errorConsumer.accept(error); } else { throw LOGGER.logExceptionAsError(new UncheckedIOException(new IOException("An error was reported during query response processing, " + System.lineSeparator() + error.toString()))); } } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse error record from " + "query response stream.")); } return null; } /** * Checks whether or not all parameters are non-null. */ private static boolean checkParametersNotNull(Object... data) { for (Object o : data) { if (o == null || o instanceof AvroNullSchema.Null) { return false; } } return true; } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformInputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryParquetSerialization) { generatedFormat.setType(QueryFormatType.PARQUET); generatedFormat.setParquetTextConfiguration(transformParquet( (BlobQueryParquetSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid input serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformOutputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryArrowSerialization) { generatedFormat.setType(QueryFormatType.ARROW); generatedFormat.setArrowConfiguration(transformArrow( (BlobQueryArrowSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid output serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a BlobQueryDelimitedSerialization into a DelimitedTextConfiguration. * * @param delimitedSerialization {@link BlobQueryDelimitedSerialization} * @return {@link DelimitedTextConfiguration} */ private static DelimitedTextConfiguration transformDelimited( BlobQueryDelimitedSerialization delimitedSerialization) { if (delimitedSerialization == null) { return null; } return new DelimitedTextConfiguration() .setColumnSeparator(charToString(delimitedSerialization.getColumnSeparator())) .setEscapeChar(charToString(delimitedSerialization.getEscapeChar())) .setFieldQuote(charToString(delimitedSerialization.getFieldQuote())) .setHeadersPresent(delimitedSerialization.isHeadersPresent()) .setRecordSeparator(charToString(delimitedSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryJsonSerialization into a JsonTextConfiguration. * * @param jsonSerialization {@link BlobQueryJsonSerialization} * @return {@link JsonTextConfiguration} */ private static JsonTextConfiguration transformJson(BlobQueryJsonSerialization jsonSerialization) { if (jsonSerialization == null) { return null; } return new JsonTextConfiguration() .setRecordSeparator(charToString(jsonSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryParquetSerialization into an Object. * * @param parquetSerialization {@link BlobQueryParquetSerialization} * @return {@link JsonTextConfiguration} */ private static Object transformParquet(BlobQueryParquetSerialization parquetSerialization) { /* This method returns an Object since the ParquetConfiguration currently accepts no options. This results in the generator generating ParquetConfiguration as an Object. */ if (parquetSerialization == null) { return null; } return new Object(); } /** * Transforms a BlobQueryArrowSerialization into a ArrowConfiguration. * * @param arrowSerialization {@link BlobQueryArrowSerialization} * @return {@link ArrowConfiguration} */ private static ArrowConfiguration transformArrow(BlobQueryArrowSerialization arrowSerialization) { if (arrowSerialization == null) { return null; } List<ArrowField> schema = arrowSerialization.getSchema() == null ? null : new ArrayList<>(arrowSerialization.getSchema().size()); if (schema != null) { for (BlobQueryArrowField field : arrowSerialization.getSchema()) { if (field == null) { schema.add(null); } else { schema.add(new ArrowField() .setName(field.getName()) .setPrecision(field.getPrecision()) .setScale(field.getScale()) .setType(field.getType().toString()) ); } } } return new ArrowConfiguration().setSchema(schema); } private static String charToString(char c) { return c == '\0' ? "" : Character.toString(c); } }
This will end up mutating the options passed by the caller, may need to copy the `options` so we don't override an external object. Or, have `listBlobContainersSegment` take the splayed out options from `ListBlobContainersOptions` instead of the options object itself. ```java listBlobContainersSegment(String marker, String prefix, Integer maxResultsPerPage, Duration timeout) ```
public PagedIterable<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options, Duration timeout) { throwOnAnonymousAccess(); BiFunction<String, Integer, PagedResponse<BlobContainerItem>> pageRetriever = (marker, pageSize) -> { ListBlobContainersOptions finalOptions = options != null ? options : new ListBlobContainersOptions(); if (pageSize != null) { finalOptions.setMaxResultsPerPage(pageSize); } return listBlobContainersSegment(marker, finalOptions, timeout); }; return new PagedIterable<>(pageSize -> pageRetriever.apply(null, pageSize), pageRetriever); }
finalOptions.setMaxResultsPerPage(pageSize);
public PagedIterable<BlobContainerItem> listBlobContainers(ListBlobContainersOptions options, Duration timeout) { throwOnAnonymousAccess(); BiFunction<String, Integer, PagedResponse<BlobContainerItem>> pageRetriever = (marker, pageSize) -> { ListBlobContainersOptions finalOptions = options != null ? options : new ListBlobContainersOptions(); Integer finalPageSize = pageSize != null ? pageSize : finalOptions.getMaxResultsPerPage(); return listBlobContainersSegment(marker, finalOptions.getDetails(), finalOptions.getPrefix(), finalPageSize, timeout); }; return new PagedIterable<>(pageSize -> pageRetriever.apply(null, pageSize), pageRetriever); }
class BlobServiceClient { private static final ClientLogger LOGGER = new ClientLogger(BlobServiceClient.class); private final AzureBlobStorageImpl azureBlobStorage; private final String accountName; private final BlobServiceVersion serviceVersion; private final CpkInfo customerProvidedKey; private final EncryptionScope encryptionScope; private final BlobContainerEncryptionScope blobContainerEncryptionScope; private final boolean anonymousAccess; /** * Package-private constructor for use by {@link BlobServiceClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param anonymousAccess Whether the client was built with anonymousAccess */ BlobServiceClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName, CpkInfo customerProvidedKey, EncryptionScope encryptionScope, BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) { /* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer when the sas token has already been applied. */ try { URI.create(url); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } this.azureBlobStorage = new AzureBlobStorageImplBuilder() .pipeline(pipeline) .url(url) .version(serviceVersion.getVersion()) .buildClient(); this.serviceVersion = serviceVersion; this.accountName = accountName; this.customerProvidedKey = customerProvidedKey; this.encryptionScope = encryptionScope; this.blobContainerEncryptionScope = blobContainerEncryptionScope; this.anonymousAccess = anonymousAccess; } /** * Initializes a {@link BlobContainerClient} object pointing to the specified container. This method does not create * a container. It simply constructs the URL to the container and offers access to methods relevant to containers. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getBlobContainerClient * <pre> * BlobContainerClient blobContainerClient = client.getBlobContainerClient& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getBlobContainerClient * * @param containerName The name of the container to point to. * @return A {@link BlobContainerClient} object pointing to the specified container */ public BlobContainerClient getBlobContainerClient(String containerName) { if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } return new BlobContainerClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return azureBlobStorage.getHttpPipeline(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return serviceVersion; } /** * Creates a new container within a storage account. If a container with the same name already exists, the operation * fails. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainer * <pre> * BlobContainerClient blobContainerClient = client.createBlobContainer& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainer * * @param containerName Name of the container to create * @return The {@link BlobContainerClient} used to interact with the container created. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobContainerClient createBlobContainer(String containerName) { return createBlobContainerWithResponse(containerName, null, null, Context.NONE).getValue(); } /** * Creates a new container within a storage account. If a container with the same name already exists, the operation * fails. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Context context = new Context& * * BlobContainerClient blobContainerClient = client.createBlobContainerWithResponse& * &quot;containerName&quot;, * metadata, * PublicAccessType.CONTAINER, * context& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse * * @param containerName Name of the container to create * @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param accessType Specifies how the data in this container is available to the public. See the * x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response * to interact with the container created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobContainerClient> createBlobContainerWithResponse(String containerName, Map<String, String> metadata, PublicAccessType accessType, Context context) { BlobContainerClient client = getBlobContainerClient(containerName); return new SimpleResponse<>(client.createWithResponse(metadata, accessType, null, context), client); } /** * Creates a new container within a storage account if it does not exist. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists * <pre> * BlobContainerClient blobContainerClient = client.createBlobContainerIfNotExists& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists * * @param containerName Name of the container to create * @return The {@link BlobContainerClient} used to interact with the container created. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobContainerClient createBlobContainerIfNotExists(String containerName) { return createBlobContainerIfNotExistsWithResponse(containerName, null, Context.NONE).getValue(); } /** * Creates a new container within a storage account if it does not exist. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Context context = new Context& * BlobContainerCreateOptions options = new BlobContainerCreateOptions& * .setPublicAccessType& * * Response&lt;BlobContainerClient&gt; response = client.createBlobContainerIfNotExistsWithResponse& * options, context& * * if & * System.out.println& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse * * @param containerName Name of the container to create * @param options {@link BlobContainerCreateOptions} * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response * to interact with the container created. If {@link Response}'s status code is 201, a new container was * successfully created. If status code is 409, a container with the same name already existed at this location. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobContainerClient> createBlobContainerIfNotExistsWithResponse(String containerName, BlobContainerCreateOptions options, Context context) { BlobContainerClient client = getBlobContainerClient(containerName); return new SimpleResponse<>(client.createIfNotExistsWithResponse(options, null, context), client); } /** * Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For * more information see the <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.deleteBlobContainer * <pre> * try & * client.deleteBlobContainer& * System.out.printf& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.deleteBlobContainer * * @param containerName Name of the container to delete */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteBlobContainer(String containerName) { deleteBlobContainerWithResponse(containerName, Context.NONE); } /** * Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For * more information see the <a href="https: * Docs</a>. * * @param containerName Name of the container to delete * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteBlobContainerWithResponse(String containerName, Context context) { return getBlobContainerClient(containerName).deleteWithResponse(null, null, context); } /** * Deletes the specified container in the storage account if it exists. For * more information see the <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists * <pre> * boolean result = client.deleteBlobContainerIfExists& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists * * @param containerName Name of the container to delete * @return {@code true} if the container is successfully deleted, {@code false} if the container does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public boolean deleteBlobContainerIfExists(String containerName) { return deleteBlobContainerIfExistsWithResponse(containerName, Context.NONE).getValue(); } /** * Deletes the specified container in the storage account if it exists. For * more information see the <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse * <pre> * Context context = new Context& * * Response&lt;Boolean&gt; response = client.deleteBlobContainerIfExistsWithResponse& * if & * System.out.println& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse * * @param containerName Name of the container to delete * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. If {@link Response}'s status code is 202, the blob * container was successfully deleted. If status code is 404, the container does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Boolean> deleteBlobContainerIfExistsWithResponse(String containerName, Context context) { return getBlobContainerClient(containerName).deleteIfExistsWithResponse(null, null, context); } /** * Gets the URL of the storage account represented by this client. * * @return the URL. */ public String getAccountUrl() { return azureBlobStorage.getUrl(); } /** * Returns a lazy loaded list of containers in this account. The returned {@link PagedIterable} can be consumed * while new items are automatically retrieved as needed. For more information, see the <a * href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.listBlobContainers --> * <pre> * client.listBlobContainers& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.listBlobContainers --> * * @return The list of containers. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BlobContainerItem> listBlobContainers() { return this.listBlobContainers(new ListBlobContainersOptions(), null); } /** * Returns a lazy loaded list of containers in this account. The returned {@link PagedIterable} can be consumed * while new items are automatically retrieved as needed. For more information, see the <a * href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.listBlobContainers * <pre> * ListBlobContainersOptions options = new ListBlobContainersOptions& * .setPrefix& * .setDetails& * * client.listBlobContainers& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.listBlobContainers * * @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service. * If iterating by page, the page size passed to byPage methods such as * {@link PagedIterable * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The list of containers. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedResponse<BlobContainerItem> listBlobContainersSegment(String marker, ListBlobContainersOptions options, Duration timeout) { List<ListBlobContainersIncludeType> include = ModelHelper.toIncludeTypes(options.getDetails()); Callable<PagedResponse<BlobContainerItem>> operation = () -> this.azureBlobStorage.getServices() .listBlobContainersSegmentSinglePage(options.getPrefix(), marker, options.getMaxResultsPerPage(), include, null, null, Context.NONE); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns a lazy loaded list of blobs in this account whose tags match the query expression. The returned * {@link PagedIterable} can be consumed while new items are automatically retrieved as needed. For more * information, including information on the query syntax, see the <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.findBlobsByTag * <pre> * client.findBlobsByTags& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.findBlobsByTag * * @param query Filters the results to return only blobs whose tags match the specified expression. * @return The list of blobs. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<TaggedBlobItem> findBlobsByTags(String query) { return this.findBlobsByTags(new FindBlobsOptions(query), null, Context.NONE); } /** * Returns a lazy loaded list of blobs in this account whose tags match the query expression. The returned * {@link PagedIterable} can be consumed while new items are automatically retrieved as needed. For more * information, including information on the query syntax, see the <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.findBlobsByTag * <pre> * Context context = new Context& * client.findBlobsByTags& * .forEach& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.findBlobsByTag * * @param options {@link FindBlobsOptions}. If iterating by page, the page size passed to byPage methods such as * {@link PagedIterable * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The list of blobs. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) { throwOnAnonymousAccess(); StorageImplUtils.assertNotNull("options", options); BiFunction<String, Integer, PagedResponse<TaggedBlobItem>> func = (marker, pageSize) -> { FindBlobsOptions finalOptions = (pageSize != null) ? new FindBlobsOptions(options.getQuery()).setMaxResultsPerPage(pageSize) : options; return findBlobsByTagsHelper(finalOptions, marker, timeout, context); }; return new PagedIterable<>(pageSize -> func.apply(null, pageSize), func); } private PagedResponse<TaggedBlobItem> findBlobsByTagsHelper(FindBlobsOptions options, String marker, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; StorageImplUtils.assertNotNull("options", options); Callable<ResponseBase<ServicesFilterBlobsHeaders, FilterBlobSegment>> operation = () -> this.azureBlobStorage.getServices().filterBlobsWithResponse(null, null, options.getQuery(), marker, options.getMaxResultsPerPage(), null, finalContext); ResponseBase<ServicesFilterBlobsHeaders, FilterBlobSegment> response = StorageImplUtils.sendRequest(operation, timeout, BlobStorageException.class); List<TaggedBlobItem> value = response.getValue().getBlobs() == null ? Collections.emptyList() : response.getValue().getBlobs().stream() .map(ModelHelper::populateTaggedBlobItem) .collect(Collectors.toList()); return new PagedResponseBase<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), value, response.getValue().getNextMarker(), response.getDeserializedHeaders()); } /** * Gets the properties of a storage account’s Blob service. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getProperties --> * <pre> * BlobServiceProperties properties = client.getProperties& * * System.out.printf& * properties.getHourMetrics& * properties.getMinuteMetrics& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getProperties --> * * @return The storage account properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobServiceProperties getProperties() { return getPropertiesWithResponse(null, Context.NONE).getValue(); } /** * Gets the properties of a storage account’s Blob service. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse * <pre> * Context context = new Context& * BlobServiceProperties properties = client.getPropertiesWithResponse& * * System.out.printf& * properties.getHourMetrics& * properties.getMinuteMetrics& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobServiceProperties> getPropertiesWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; throwOnAnonymousAccess(); Callable<ResponseBase<ServicesGetPropertiesHeaders, BlobServiceProperties>> operation = () -> this.azureBlobStorage.getServices().getPropertiesWithResponse(null, null, finalContext); ResponseBase<ServicesGetPropertiesHeaders, BlobServiceProperties> response = StorageImplUtils.sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, response.getValue()); } /** * Sets properties for a storage account's Blob service endpoint. For more information, see the * <a href="https: * Note that setting the default service version has no effect when using this client because this client explicitly * sets the version header on each request, overriding the default. * <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs. * If CORS policies are set, CORS parameters that are not set default to the empty string.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.setProperties * <pre> * BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy& * BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy& * * BlobServiceProperties properties = new BlobServiceProperties& * .setLogging& * .setWrite& * .setDelete& * .setVersion& * .setRetentionPolicy& * .setHourMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * .setMinuteMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * * try & * client.setProperties& * System.out.printf& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.setProperties * * @param properties Configures the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setProperties(BlobServiceProperties properties) { setPropertiesWithResponse(properties, null, Context.NONE); } /** * Sets properties for a storage account's Blob service endpoint. For more information, see the * <a href="https: * Note that setting the default service version has no effect when using this client because this client explicitly * sets the version header on each request, overriding the default. * <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs. * If CORS policies are set, CORS parameters that are not set default to the empty string.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse * <pre> * BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy& * BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy& * * BlobServiceProperties properties = new BlobServiceProperties& * .setLogging& * .setWrite& * .setDelete& * .setVersion& * .setRetentionPolicy& * .setHourMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * .setMinuteMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * * Context context = new Context& * * System.out.printf& * client.setPropertiesWithResponse& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse * * @param properties Configures the service. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The storage account properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setPropertiesWithResponse(BlobServiceProperties properties, Duration timeout, Context context) { throwOnAnonymousAccess(); BlobServiceProperties finalProperties; if (properties != null) { finalProperties = new BlobServiceProperties(); finalProperties.setLogging(properties.getLogging()); if (finalProperties.getLogging() != null) { StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion()); ModelHelper.validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy"); } finalProperties.setHourMetrics(properties.getHourMetrics()); if (finalProperties.getHourMetrics() != null) { StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion()); ModelHelper.validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention " + "Policy"); if (finalProperties.getHourMetrics().isEnabled()) { StorageImplUtils.assertNotNull("HourMetrics IncludeApis", finalProperties.getHourMetrics().isIncludeApis()); } } finalProperties.setMinuteMetrics(properties.getMinuteMetrics()); if (finalProperties.getMinuteMetrics() != null) { StorageImplUtils.assertNotNull("MinuteMetrics Version", finalProperties.getMinuteMetrics().getVersion()); ModelHelper.validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics " + "Retention Policy"); if (finalProperties.getMinuteMetrics().isEnabled()) { StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis", finalProperties.getHourMetrics().isIncludeApis()); } } if (properties.getCors() != null) { List<BlobCorsRule> corsRules = new ArrayList<>(); for (BlobCorsRule rule : properties.getCors()) { corsRules.add(ModelHelper.validatedCorsRule(rule)); } finalProperties.setCors(corsRules); } finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion()); finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy()); ModelHelper.validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days"); finalProperties.setStaticWebsite(properties.getStaticWebsite()); } else { finalProperties = null; } Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getServices() .setPropertiesNoCustomHeadersWithResponse(finalProperties, null, null, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when * using {@link TokenCredential} in this object's {@link HttpPipeline}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getUserDelegationKey * <pre> * System.out.printf& * client.getUserDelegationKey& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getUserDelegationKey * * @param start Start time for the key's validity. Null indicates immediate start. * @param expiry Expiration of the key's validity. * @return The user delegation key. */ @ServiceMethod(returns = ReturnType.SINGLE) public UserDelegationKey getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) { return getUserDelegationKeyWithResponse(start, expiry, null, Context.NONE).getValue(); } /** * Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when * using {@link TokenCredential} in this object's {@link HttpPipeline}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse * <pre> * System.out.printf& * client.getUserDelegationKeyWithResponse& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse * * @param start Start time for the key's validity. Null indicates immediate start. * @param expiry Expiration of the key's validity. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<UserDelegationKey> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry, Duration timeout, Context context) { StorageImplUtils.assertNotNull("expiry", expiry); if (start != null && !start.isBefore(expiry)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("`start` must be null or a datetime before `expiry`.")); } throwOnAnonymousAccess(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ServicesGetUserDelegationKeyHeaders, UserDelegationKey>> operation = () -> this.azureBlobStorage.getServices().getUserDelegationKeyWithResponse(new KeyInfo() .setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start)) .setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)), null, null, finalContext); ResponseBase<ServicesGetUserDelegationKeyHeaders, UserDelegationKey> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, response.getValue()); } /** * Retrieves statistics related to replication for the Blob service. It is only available on the secondary location * endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see * the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getStatistics --> * <pre> * System.out.printf& * client.getStatistics& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getStatistics --> * * @return The storage account statistics. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobServiceStatistics getStatistics() { return getStatisticsWithResponse(null, Context.NONE).getValue(); } /** * Retrieves statistics related to replication for the Blob service. It is only available on the secondary location * endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see * the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse * <pre> * System.out.printf& * client.getStatisticsWithResponse& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobServiceStatistics> getStatisticsWithResponse(Duration timeout, Context context) { throwOnAnonymousAccess(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ServicesGetStatisticsHeaders, BlobServiceStatistics>> operation = () -> this.azureBlobStorage.getServices().getStatisticsWithResponse(null, null, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns the sku name and account kind for the account. For more information, please see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getAccountInfo --> * <pre> * StorageAccountInfo accountInfo = client.getAccountInfo& * * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getAccountInfo --> * * @return The storage account info. */ @ServiceMethod(returns = ReturnType.SINGLE) public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. For more information, please see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { throwOnAnonymousAccess(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ServicesGetAccountInfoHeaders, Void>> operation = () -> this.azureBlobStorage.getServices().getAccountInfoWithResponse(finalContext); ResponseBase<ServicesGetAccountInfoHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); ServicesGetAccountInfoHeaders hd = response.getDeserializedHeaders(); return new SimpleResponse<>(response, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind(), hd.isXMsIsHnsEnabled())); } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return this.accountName; } /** * Checks if service client was built with credentials. */ private void throwOnAnonymousAccess() { if (anonymousAccess) { throw LOGGER.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without " + "credentials")); } } /** * Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}. * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p> * * <p><strong>Generating an account SAS</strong></p> * <p>The snippet below generates an AccountSasSignatureValues object that lasts for two days and gives the user * read and list access to blob and file shares.</p> * <!-- src_embed com.azure.storage.blob.BlobServiceClient.generateAccountSas * <pre> * AccountSasPermission permissions = new AccountSasPermission& * .setListPermission& * .setReadPermission& * AccountSasResourceType resourceTypes = new AccountSasResourceType& * AccountSasService services = new AccountSasService& * OffsetDateTime expiryTime = OffsetDateTime.now& * * AccountSasSignatureValues sasValues = * new AccountSasSignatureValues& * * & * String sas = client.generateAccountSas& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.generateAccountSas * * @param accountSasSignatureValues {@link AccountSasSignatureValues} * * @return A {@code String} representing the SAS query parameters. */ public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) { return generateAccountSas(accountSasSignatureValues, Context.NONE); } /* TODO(gapra): REST Docs*/ /** * Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}. * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p> * * <p><strong>Generating an account SAS</strong></p> * <p>The snippet below generates an AccountSasSignatureValues object that lasts for two days and gives the user * read and list access to blob and file shares.</p> * <!-- src_embed com.azure.storage.blob.BlobServiceClient.generateAccountSas * <pre> * AccountSasPermission permissions = new AccountSasPermission& * .setListPermission& * .setReadPermission& * AccountSasResourceType resourceTypes = new AccountSasResourceType& * AccountSasService services = new AccountSasService& * OffsetDateTime expiryTime = OffsetDateTime.now& * * AccountSasSignatureValues sasValues = * new AccountSasSignatureValues& * * & * String sas = client.generateAccountSas& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.generateAccountSas * * @param accountSasSignatureValues {@link AccountSasSignatureValues} * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) { throwOnAnonymousAccess(); return new AccountSasImplUtil(accountSasSignatureValues, this.encryptionScope == null ? null : this.encryptionScope.getEncryptionScope()) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context); } /** * Restores a previously deleted container. * If the container associated with provided <code>deletedContainerName</code> * already exists, this call will result in a 409 (conflict). * This API is only functional if Container Soft Delete is enabled * for the storage account associated with the container. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer * <pre> * ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions& * listBlobContainersOptions.getDetails& * client.listBlobContainers& * deletedContainer -&gt; & * BlobContainerClient blobContainerClient = client.undeleteBlobContainer& * deletedContainer.getName& * & * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer * * @param deletedContainerName The name of the previously deleted container. * @param deletedContainerVersion The version of the previously deleted container. * @return The {@link BlobContainerClient} used to interact with the restored container. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobContainerClient undeleteBlobContainer(String deletedContainerName, String deletedContainerVersion) { return this.undeleteBlobContainerWithResponse( new UndeleteBlobContainerOptions(deletedContainerName, deletedContainerVersion), null, Context.NONE).getValue(); } /** * Restores a previously deleted container. The restored container * will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>. * Otherwise <code>deletedContainerName</code> is used as destination container name. * If the container associated with provided <code>destinationContainerName</code> * already exists, this call will result in a 409 (conflict). * This API is only functional if Container Soft Delete is enabled * for the storage account associated with the container. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse * <pre> * ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions& * listBlobContainersOptions.getDetails& * client.listBlobContainers& * deletedContainer -&gt; & * BlobContainerClient blobContainerClient = client.undeleteBlobContainerWithResponse& * new UndeleteBlobContainerOptions& * timeout, context& * & * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse * * @param options {@link UndeleteBlobContainerOptions}. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response * to interact with the restored container. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobContainerClient> undeleteBlobContainerWithResponse(UndeleteBlobContainerOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null; String finalDestinationContainerName = hasOptionalDestinationContainerName ? options.getDestinationContainerName() : options.getDeletedContainerName(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ContainersRestoreHeaders, Void>> operation = () -> this.azureBlobStorage.getContainers().restoreWithResponse(finalDestinationContainerName, null, null, options.getDeletedContainerName(), options.getDeletedContainerVersion(), finalContext); ResponseBase<ContainersRestoreHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, getBlobContainerClient(finalDestinationContainerName)); } }
class BlobServiceClient { private static final ClientLogger LOGGER = new ClientLogger(BlobServiceClient.class); private final AzureBlobStorageImpl azureBlobStorage; private final String accountName; private final BlobServiceVersion serviceVersion; private final CpkInfo customerProvidedKey; private final EncryptionScope encryptionScope; private final BlobContainerEncryptionScope blobContainerEncryptionScope; private final boolean anonymousAccess; /** * Package-private constructor for use by {@link BlobServiceClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param anonymousAccess Whether the client was built with anonymousAccess */ BlobServiceClient(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName, CpkInfo customerProvidedKey, EncryptionScope encryptionScope, BlobContainerEncryptionScope blobContainerEncryptionScope, boolean anonymousAccess) { /* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer when the sas token has already been applied. */ try { URI.create(url); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } this.azureBlobStorage = new AzureBlobStorageImplBuilder() .pipeline(pipeline) .url(url) .version(serviceVersion.getVersion()) .buildClient(); this.serviceVersion = serviceVersion; this.accountName = accountName; this.customerProvidedKey = customerProvidedKey; this.encryptionScope = encryptionScope; this.blobContainerEncryptionScope = blobContainerEncryptionScope; this.anonymousAccess = anonymousAccess; } /** * Initializes a {@link BlobContainerClient} object pointing to the specified container. This method does not create * a container. It simply constructs the URL to the container and offers access to methods relevant to containers. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getBlobContainerClient * <pre> * BlobContainerClient blobContainerClient = client.getBlobContainerClient& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getBlobContainerClient * * @param containerName The name of the container to point to. * @return A {@link BlobContainerClient} object pointing to the specified container */ public BlobContainerClient getBlobContainerClient(String containerName) { if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } return new BlobContainerClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), containerName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return azureBlobStorage.getHttpPipeline(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return serviceVersion; } /** * Creates a new container within a storage account. If a container with the same name already exists, the operation * fails. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainer * <pre> * BlobContainerClient blobContainerClient = client.createBlobContainer& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainer * * @param containerName Name of the container to create * @return The {@link BlobContainerClient} used to interact with the container created. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobContainerClient createBlobContainer(String containerName) { return createBlobContainerWithResponse(containerName, null, null, Context.NONE).getValue(); } /** * Creates a new container within a storage account. If a container with the same name already exists, the operation * fails. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Context context = new Context& * * BlobContainerClient blobContainerClient = client.createBlobContainerWithResponse& * &quot;containerName&quot;, * metadata, * PublicAccessType.CONTAINER, * context& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse * * @param containerName Name of the container to create * @param metadata Metadata to associate with the container. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param accessType Specifies how the data in this container is available to the public. See the * x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response * to interact with the container created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobContainerClient> createBlobContainerWithResponse(String containerName, Map<String, String> metadata, PublicAccessType accessType, Context context) { BlobContainerClient client = getBlobContainerClient(containerName); return new SimpleResponse<>(client.createWithResponse(metadata, accessType, null, context), client); } /** * Creates a new container within a storage account if it does not exist. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists * <pre> * BlobContainerClient blobContainerClient = client.createBlobContainerIfNotExists& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists * * @param containerName Name of the container to create * @return The {@link BlobContainerClient} used to interact with the container created. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobContainerClient createBlobContainerIfNotExists(String containerName) { return createBlobContainerIfNotExistsWithResponse(containerName, null, Context.NONE).getValue(); } /** * Creates a new container within a storage account if it does not exist. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Context context = new Context& * BlobContainerCreateOptions options = new BlobContainerCreateOptions& * .setPublicAccessType& * * Response&lt;BlobContainerClient&gt; response = client.createBlobContainerIfNotExistsWithResponse& * options, context& * * if & * System.out.println& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse * * @param containerName Name of the container to create * @param options {@link BlobContainerCreateOptions} * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response * to interact with the container created. If {@link Response}'s status code is 201, a new container was * successfully created. If status code is 409, a container with the same name already existed at this location. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobContainerClient> createBlobContainerIfNotExistsWithResponse(String containerName, BlobContainerCreateOptions options, Context context) { BlobContainerClient client = getBlobContainerClient(containerName); return new SimpleResponse<>(client.createIfNotExistsWithResponse(options, null, context), client); } /** * Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For * more information see the <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.deleteBlobContainer * <pre> * try & * client.deleteBlobContainer& * System.out.printf& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.deleteBlobContainer * * @param containerName Name of the container to delete */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteBlobContainer(String containerName) { deleteBlobContainerWithResponse(containerName, Context.NONE); } /** * Deletes the specified container in the storage account. If the container doesn't exist the operation fails. For * more information see the <a href="https: * Docs</a>. * * @param containerName Name of the container to delete * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteBlobContainerWithResponse(String containerName, Context context) { return getBlobContainerClient(containerName).deleteWithResponse(null, null, context); } /** * Deletes the specified container in the storage account if it exists. For * more information see the <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists * <pre> * boolean result = client.deleteBlobContainerIfExists& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists * * @param containerName Name of the container to delete * @return {@code true} if the container is successfully deleted, {@code false} if the container does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public boolean deleteBlobContainerIfExists(String containerName) { return deleteBlobContainerIfExistsWithResponse(containerName, Context.NONE).getValue(); } /** * Deletes the specified container in the storage account if it exists. For * more information see the <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse * <pre> * Context context = new Context& * * Response&lt;Boolean&gt; response = client.deleteBlobContainerIfExistsWithResponse& * if & * System.out.println& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse * * @param containerName Name of the container to delete * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. If {@link Response}'s status code is 202, the blob * container was successfully deleted. If status code is 404, the container does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Boolean> deleteBlobContainerIfExistsWithResponse(String containerName, Context context) { return getBlobContainerClient(containerName).deleteIfExistsWithResponse(null, null, context); } /** * Gets the URL of the storage account represented by this client. * * @return the URL. */ public String getAccountUrl() { return azureBlobStorage.getUrl(); } /** * Returns a lazy loaded list of containers in this account. The returned {@link PagedIterable} can be consumed * while new items are automatically retrieved as needed. For more information, see the <a * href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.listBlobContainers --> * <pre> * client.listBlobContainers& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.listBlobContainers --> * * @return The list of containers. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BlobContainerItem> listBlobContainers() { return this.listBlobContainers(new ListBlobContainersOptions(), null); } /** * Returns a lazy loaded list of containers in this account. The returned {@link PagedIterable} can be consumed * while new items are automatically retrieved as needed. For more information, see the <a * href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.listBlobContainers * <pre> * ListBlobContainersOptions options = new ListBlobContainersOptions& * .setPrefix& * .setDetails& * * client.listBlobContainers& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.listBlobContainers * * @param options A {@link ListBlobContainersOptions} which specifies what data should be returned by the service. * If iterating by page, the page size passed to byPage methods such as * {@link PagedIterable * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The list of containers. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedResponse<BlobContainerItem> listBlobContainersSegment(String marker, BlobContainerListDetails details, String prefix, Integer maxResultsPerPage, Duration timeout) { List<ListBlobContainersIncludeType> include = ModelHelper.toIncludeTypes(details); Callable<PagedResponse<BlobContainerItem>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().listBlobContainersSegmentSinglePage(prefix, marker, maxResultsPerPage, include, null, null, Context.NONE)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns a lazy loaded list of blobs in this account whose tags match the query expression. The returned * {@link PagedIterable} can be consumed while new items are automatically retrieved as needed. For more * information, including information on the query syntax, see the <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.findBlobsByTag * <pre> * client.findBlobsByTags& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.findBlobsByTag * * @param query Filters the results to return only blobs whose tags match the specified expression. * @return The list of blobs. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<TaggedBlobItem> findBlobsByTags(String query) { return this.findBlobsByTags(new FindBlobsOptions(query), null, Context.NONE); } /** * Returns a lazy loaded list of blobs in this account whose tags match the query expression. The returned * {@link PagedIterable} can be consumed while new items are automatically retrieved as needed. For more * information, including information on the query syntax, see the <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.findBlobsByTag * <pre> * Context context = new Context& * client.findBlobsByTags& * .forEach& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.findBlobsByTag * * @param options {@link FindBlobsOptions}. If iterating by page, the page size passed to byPage methods such as * {@link PagedIterable * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The list of blobs. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<TaggedBlobItem> findBlobsByTags(FindBlobsOptions options, Duration timeout, Context context) { throwOnAnonymousAccess(); StorageImplUtils.assertNotNull("options", options); BiFunction<String, Integer, PagedResponse<TaggedBlobItem>> func = (marker, pageSize) -> { FindBlobsOptions finalOptions = (pageSize != null) ? new FindBlobsOptions(options.getQuery()).setMaxResultsPerPage(pageSize) : options; return findBlobsByTagsHelper(finalOptions, marker, timeout, context); }; return new PagedIterable<>(pageSize -> func.apply(null, pageSize), func); } private PagedResponse<TaggedBlobItem> findBlobsByTagsHelper(FindBlobsOptions options, String marker, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; StorageImplUtils.assertNotNull("options", options); Callable<ResponseBase<ServicesFilterBlobsHeaders, FilterBlobSegment>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().filterBlobsWithResponse(null, null, options.getQuery(), marker, options.getMaxResultsPerPage(), null, finalContext)); ResponseBase<ServicesFilterBlobsHeaders, FilterBlobSegment> response = StorageImplUtils.sendRequest(operation, timeout, BlobStorageException.class); List<TaggedBlobItem> value = response.getValue().getBlobs().stream() .map(ModelHelper::populateTaggedBlobItem) .collect(Collectors.toList()); return new PagedResponseBase<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), value, response.getValue().getNextMarker(), response.getDeserializedHeaders()); } /** * Gets the properties of a storage account’s Blob service. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getProperties --> * <pre> * BlobServiceProperties properties = client.getProperties& * * System.out.printf& * properties.getHourMetrics& * properties.getMinuteMetrics& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getProperties --> * * @return The storage account properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobServiceProperties getProperties() { return getPropertiesWithResponse(null, Context.NONE).getValue(); } /** * Gets the properties of a storage account’s Blob service. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse * <pre> * Context context = new Context& * BlobServiceProperties properties = client.getPropertiesWithResponse& * * System.out.printf& * properties.getHourMetrics& * properties.getMinuteMetrics& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobServiceProperties> getPropertiesWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; throwOnAnonymousAccess(); Callable<ResponseBase<ServicesGetPropertiesHeaders, BlobServiceProperties>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().getPropertiesWithResponse(null, null, finalContext)); ResponseBase<ServicesGetPropertiesHeaders, BlobServiceProperties> response = StorageImplUtils.sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, response.getValue()); } /** * Sets properties for a storage account's Blob service endpoint. For more information, see the * <a href="https: * Note that setting the default service version has no effect when using this client because this client explicitly * sets the version header on each request, overriding the default. * <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs. * If CORS policies are set, CORS parameters that are not set default to the empty string.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.setProperties * <pre> * BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy& * BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy& * * BlobServiceProperties properties = new BlobServiceProperties& * .setLogging& * .setWrite& * .setDelete& * .setVersion& * .setRetentionPolicy& * .setHourMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * .setMinuteMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * * try & * client.setProperties& * System.out.printf& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.setProperties * * @param properties Configures the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setProperties(BlobServiceProperties properties) { setPropertiesWithResponse(properties, null, Context.NONE); } /** * Sets properties for a storage account's Blob service endpoint. For more information, see the * <a href="https: * Note that setting the default service version has no effect when using this client because this client explicitly * sets the version header on each request, overriding the default. * <p>This method checks to ensure the properties being sent follow the specifications indicated in the Azure Docs. * If CORS policies are set, CORS parameters that are not set default to the empty string.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse * <pre> * BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy& * BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy& * * BlobServiceProperties properties = new BlobServiceProperties& * .setLogging& * .setWrite& * .setDelete& * .setVersion& * .setRetentionPolicy& * .setHourMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * .setMinuteMetrics& * .setEnabled& * .setVersion& * .setIncludeApis& * .setRetentionPolicy& * * Context context = new Context& * * System.out.printf& * client.setPropertiesWithResponse& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse * * @param properties Configures the service. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The storage account properties. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setPropertiesWithResponse(BlobServiceProperties properties, Duration timeout, Context context) { throwOnAnonymousAccess(); BlobServiceProperties finalProperties; if (properties != null) { finalProperties = new BlobServiceProperties(); finalProperties.setLogging(properties.getLogging()); if (finalProperties.getLogging() != null) { StorageImplUtils.assertNotNull("Logging Version", finalProperties.getLogging().getVersion()); ModelHelper.validateRetentionPolicy(finalProperties.getLogging().getRetentionPolicy(), "Logging Retention Policy"); } finalProperties.setHourMetrics(properties.getHourMetrics()); if (finalProperties.getHourMetrics() != null) { StorageImplUtils.assertNotNull("HourMetrics Version", finalProperties.getHourMetrics().getVersion()); ModelHelper.validateRetentionPolicy(finalProperties.getHourMetrics().getRetentionPolicy(), "HourMetrics Retention " + "Policy"); if (finalProperties.getHourMetrics().isEnabled()) { StorageImplUtils.assertNotNull("HourMetrics IncludeApis", finalProperties.getHourMetrics().isIncludeApis()); } } finalProperties.setMinuteMetrics(properties.getMinuteMetrics()); if (finalProperties.getMinuteMetrics() != null) { StorageImplUtils.assertNotNull("MinuteMetrics Version", finalProperties.getMinuteMetrics().getVersion()); ModelHelper.validateRetentionPolicy(finalProperties.getMinuteMetrics().getRetentionPolicy(), "MinuteMetrics " + "Retention Policy"); if (finalProperties.getMinuteMetrics().isEnabled()) { StorageImplUtils.assertNotNull("MinuteMetrics IncludeApis", finalProperties.getHourMetrics().isIncludeApis()); } } List<BlobCorsRule> corsRules = new ArrayList<>(); for (BlobCorsRule rule : properties.getCors()) { corsRules.add(ModelHelper.validatedCorsRule(rule)); } finalProperties.setCors(corsRules); finalProperties.setDefaultServiceVersion(properties.getDefaultServiceVersion()); finalProperties.setDeleteRetentionPolicy(properties.getDeleteRetentionPolicy()); ModelHelper.validateRetentionPolicy(finalProperties.getDeleteRetentionPolicy(), "DeleteRetentionPolicy Days"); finalProperties.setStaticWebsite(properties.getStaticWebsite()); } else { finalProperties = null; } Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().setPropertiesNoCustomHeadersWithResponse(finalProperties, null, null, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when * using {@link TokenCredential} in this object's {@link HttpPipeline}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getUserDelegationKey * <pre> * System.out.printf& * client.getUserDelegationKey& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getUserDelegationKey * * @param start Start time for the key's validity. Null indicates immediate start. * @param expiry Expiration of the key's validity. * @return The user delegation key. */ @ServiceMethod(returns = ReturnType.SINGLE) public UserDelegationKey getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) { return getUserDelegationKeyWithResponse(start, expiry, null, Context.NONE).getValue(); } /** * Gets a user delegation key for use with this account's blob storage. Note: This method call is only valid when * using {@link TokenCredential} in this object's {@link HttpPipeline}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse * <pre> * System.out.printf& * client.getUserDelegationKeyWithResponse& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse * * @param start Start time for the key's validity. Null indicates immediate start. * @param expiry Expiration of the key's validity. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<UserDelegationKey> getUserDelegationKeyWithResponse(OffsetDateTime start, OffsetDateTime expiry, Duration timeout, Context context) { StorageImplUtils.assertNotNull("expiry", expiry); if (start != null && !start.isBefore(expiry)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("`start` must be null or a datetime before `expiry`.")); } throwOnAnonymousAccess(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ServicesGetUserDelegationKeyHeaders, UserDelegationKey>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().getUserDelegationKeyWithResponse(new KeyInfo() .setStart(start == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(start)) .setExpiry(Constants.ISO_8601_UTC_DATE_FORMATTER.format(expiry)), null, null, finalContext)); ResponseBase<ServicesGetUserDelegationKeyHeaders, UserDelegationKey> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, response.getValue()); } /** * Retrieves statistics related to replication for the Blob service. It is only available on the secondary location * endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see * the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getStatistics --> * <pre> * System.out.printf& * client.getStatistics& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getStatistics --> * * @return The storage account statistics. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobServiceStatistics getStatistics() { return getStatisticsWithResponse(null, Context.NONE).getValue(); } /** * Retrieves statistics related to replication for the Blob service. It is only available on the secondary location * endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see * the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse * <pre> * System.out.printf& * client.getStatisticsWithResponse& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobServiceStatistics> getStatisticsWithResponse(Duration timeout, Context context) { throwOnAnonymousAccess(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ServicesGetStatisticsHeaders, BlobServiceStatistics>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().getStatisticsWithResponse(null, null, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns the sku name and account kind for the account. For more information, please see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.getAccountInfo --> * <pre> * StorageAccountInfo accountInfo = client.getAccountInfo& * * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.getAccountInfo --> * * @return The storage account info. */ @ServiceMethod(returns = ReturnType.SINGLE) public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. For more information, please see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { throwOnAnonymousAccess(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ServicesGetAccountInfoHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getServices().getAccountInfoWithResponse(finalContext)); ResponseBase<ServicesGetAccountInfoHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); ServicesGetAccountInfoHeaders hd = response.getDeserializedHeaders(); return new SimpleResponse<>(response, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind(), hd.isXMsIsHnsEnabled())); } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return this.accountName; } /** * Checks if service client was built with credentials. */ private void throwOnAnonymousAccess() { if (anonymousAccess) { throw LOGGER.logExceptionAsError(new IllegalStateException("Service client cannot be accessed without " + "credentials")); } } /** * Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}. * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p> * * <p><strong>Generating an account SAS</strong></p> * <p>The snippet below generates an AccountSasSignatureValues object that lasts for two days and gives the user * read and list access to blob and file shares.</p> * <!-- src_embed com.azure.storage.blob.BlobServiceClient.generateAccountSas * <pre> * AccountSasPermission permissions = new AccountSasPermission& * .setListPermission& * .setReadPermission& * AccountSasResourceType resourceTypes = new AccountSasResourceType& * AccountSasService services = new AccountSasService& * OffsetDateTime expiryTime = OffsetDateTime.now& * * AccountSasSignatureValues sasValues = * new AccountSasSignatureValues& * * & * String sas = client.generateAccountSas& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.generateAccountSas * * @param accountSasSignatureValues {@link AccountSasSignatureValues} * * @return A {@code String} representing the SAS query parameters. */ public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) { return generateAccountSas(accountSasSignatureValues, Context.NONE); } /* TODO(gapra): REST Docs*/ /** * Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}. * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p> * * <p><strong>Generating an account SAS</strong></p> * <p>The snippet below generates an AccountSasSignatureValues object that lasts for two days and gives the user * read and list access to blob and file shares.</p> * <!-- src_embed com.azure.storage.blob.BlobServiceClient.generateAccountSas * <pre> * AccountSasPermission permissions = new AccountSasPermission& * .setListPermission& * .setReadPermission& * AccountSasResourceType resourceTypes = new AccountSasResourceType& * AccountSasService services = new AccountSasService& * OffsetDateTime expiryTime = OffsetDateTime.now& * * AccountSasSignatureValues sasValues = * new AccountSasSignatureValues& * * & * String sas = client.generateAccountSas& * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.generateAccountSas * * @param accountSasSignatureValues {@link AccountSasSignatureValues} * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Context context) { return generateAccountSas(accountSasSignatureValues, null, context); } /** * Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}. * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.</p> * * @param accountSasSignatureValues {@link AccountSasSignatureValues} * @param stringToSignHandler For debugging purposes only. Returns the string to sign that was used to generate the * signature. * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues, Consumer<String> stringToSignHandler, Context context) { throwOnAnonymousAccess(); return new AccountSasImplUtil(accountSasSignatureValues, this.encryptionScope == null ? null : this.encryptionScope.getEncryptionScope()) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), stringToSignHandler, context); } /** * Restores a previously deleted container. * If the container associated with provided <code>deletedContainerName</code> * already exists, this call will result in a 409 (conflict). * This API is only functional if Container Soft Delete is enabled * for the storage account associated with the container. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer * <pre> * ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions& * listBlobContainersOptions.getDetails& * client.listBlobContainers& * deletedContainer -&gt; & * BlobContainerClient blobContainerClient = client.undeleteBlobContainer& * deletedContainer.getName& * & * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer * * @param deletedContainerName The name of the previously deleted container. * @param deletedContainerVersion The version of the previously deleted container. * @return The {@link BlobContainerClient} used to interact with the restored container. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobContainerClient undeleteBlobContainer(String deletedContainerName, String deletedContainerVersion) { return this.undeleteBlobContainerWithResponse( new UndeleteBlobContainerOptions(deletedContainerName, deletedContainerVersion), null, Context.NONE).getValue(); } /** * Restores a previously deleted container. The restored container * will be renamed to the <code>destinationContainerName</code> if provided in <code>options</code>. * Otherwise <code>deletedContainerName</code> is used as destination container name. * If the container associated with provided <code>destinationContainerName</code> * already exists, this call will result in a 409 (conflict). * This API is only functional if Container Soft Delete is enabled * for the storage account associated with the container. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse * <pre> * ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions& * listBlobContainersOptions.getDetails& * client.listBlobContainers& * deletedContainer -&gt; & * BlobContainerClient blobContainerClient = client.undeleteBlobContainerWithResponse& * new UndeleteBlobContainerOptions& * timeout, context& * & * & * </pre> * <!-- end com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse * * @param options {@link UndeleteBlobContainerOptions}. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Response} whose {@link Response * to interact with the restored container. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobContainerClient> undeleteBlobContainerWithResponse(UndeleteBlobContainerOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); boolean hasOptionalDestinationContainerName = options.getDestinationContainerName() != null; String finalDestinationContainerName = hasOptionalDestinationContainerName ? options.getDestinationContainerName() : options.getDeletedContainerName(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<ContainersRestoreHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getContainers().restoreWithResponse(finalDestinationContainerName, null, null, options.getDeletedContainerName(), options.getDeletedContainerVersion(), finalContext)); ResponseBase<ContainersRestoreHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, getBlobContainerClient(finalDestinationContainerName)); } }
This changed the scope of the `timeout`. Before it included writing the response to the `OutputStream`, it no longer includes that.
public BlobQueryResponse queryWithResponse(BlobQueryOptions queryOptions, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", queryOptions); StorageImplUtils.assertNotNull("outputStream", queryOptions.getOutputStream()); Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions requestConditions = queryOptions.getRequestConditions() == null ? new BlobRequestConditions() : queryOptions.getRequestConditions(); QuerySerialization in = BlobQueryReader.transformInputSerialization(queryOptions.getInputSerialization(), LOGGER); QuerySerialization out = BlobQueryReader.transformOutputSerialization(queryOptions.getOutputSerialization(), LOGGER); QueryRequest qr = new QueryRequest() .setExpression(queryOptions.getExpression()) .setInputSerialization(in) .setOutputSerialization(out); Callable<ResponseBase<BlobsQueryHeaders, InputStream>> operation = () -> this.azureBlobStorage.getBlobs().queryWithResponse(containerName, blobName, getSnapshotId(), null, requestConditions.getLeaseId(), requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null, qr, getCustomerProvidedKey(), finalContext); try { ResponseBase<BlobsQueryHeaders, InputStream> response = sendRequest(operation, timeout, BlobStorageException.class); InputStream avroInputStream = response.getValue(); BlobQueryReader reader = new BlobQueryReader(null, queryOptions.getProgressConsumer(), queryOptions.getErrorConsumer()); InputStream resultStream = reader.readInputStream(avroInputStream); OutputStream outputStream = queryOptions.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = resultStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } BlobQueryAsyncResponse asyncResponse = new BlobQueryAsyncResponse(response.getRequest(), response.getStatusCode(), response.getHeaders(), /* Parse the avro reactive stream. */ null, ModelHelper.transformQueryHeaders(response.getDeserializedHeaders(), response.getHeaders())); return new BlobQueryResponse(asyncResponse); } catch (IOException e) { throw new UncheckedIOException("Failed to read query results or write to the output stream", e); } }
ResponseBase<BlobsQueryHeaders, InputStream> response = sendRequest(operation, timeout,
public BlobQueryResponse queryWithResponse(BlobQueryOptions queryOptions, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", queryOptions); StorageImplUtils.assertNotNull("outputStream", queryOptions.getOutputStream()); Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions requestConditions = queryOptions.getRequestConditions() == null ? new BlobRequestConditions() : queryOptions.getRequestConditions(); QuerySerialization in = BlobQueryReader.transformInputSerialization(queryOptions.getInputSerialization(), LOGGER); QuerySerialization out = BlobQueryReader.transformOutputSerialization(queryOptions.getOutputSerialization(), LOGGER); QueryRequest qr = new QueryRequest() .setExpression(queryOptions.getExpression()) .setInputSerialization(in) .setOutputSerialization(out); Callable<ResponseBase<BlobsQueryHeaders, InputStream>> operation = () -> { ResponseBase<BlobsQueryHeaders, InputStream> response = wrapServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().queryWithResponse(containerName, blobName, getSnapshotId(), null, requestConditions.getLeaseId(), requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null, qr, getCustomerProvidedKey(), finalContext)); InputStream avroInputStream = response.getValue(); BlobQueryReader reader = new BlobQueryReader(null, queryOptions.getProgressConsumer(), queryOptions.getErrorConsumer()); InputStream resultStream = reader.readInputStream(avroInputStream); OutputStream outputStream = queryOptions.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = resultStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } return response; }; ResponseBase<BlobsQueryHeaders, InputStream> response = sendRequest(operation, timeout, BlobStorageException.class); BlobQueryAsyncResponse asyncResponse = new BlobQueryAsyncResponse(response.getRequest(), response.getStatusCode(), response.getHeaders(), null, ModelHelper.transformQueryHeaders(response.getDeserializedHeaders(), response.getHeaders())); return new BlobQueryResponse(asyncResponse); }
class BlobClientBase { private static final ClientLogger LOGGER = new ClientLogger(BlobClientBase.class); private static final Set<OpenOption> DEFAULT_OPEN_OPTIONS_SET = Collections.unmodifiableSet(new HashSet<>( Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE))); /** * Backing REST client for the blob client. */ protected final AzureBlobStorageImpl azureBlobStorage; private final String snapshot; private final String versionId; private final CpkInfo customerProvidedKey; /** * Encryption scope of the blob. */ protected final EncryptionScope encryptionScope; /** * Storage account name that contains the blob. */ protected final String accountName; /** * Container name that contains the blob. */ protected final String containerName; /** * Name of the blob. */ protected final String blobName; /** * Storage REST API version used in requests to the Storage service. */ protected final BlobServiceVersion serviceVersion; private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this(client, client.getHttpPipeline(), client.getAccountUrl(), client.getServiceVersion(), client.getAccountName(), client.getContainerName(), client.getBlobName(), client.getSnapshotId(), client.getCustomerProvidedKey(), new EncryptionScope().setEncryptionScope(client.getEncryptionScope()), client.getVersionId()); } /** * Protected constructor for use by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param containerName The container name. * @param blobName The blob name. * @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly. * @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param versionId The version identifier for the blob, pass {@code null} to interact with the latest blob version. */ protected BlobClientBase(BlobAsyncClientBase client, HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey, EncryptionScope encryptionScope, String versionId) { if (snapshot != null && versionId != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.client = client; this.azureBlobStorage = new AzureBlobStorageImplBuilder() .pipeline(pipeline) .url(url) .version(serviceVersion.getVersion()) .buildClient(); this.serviceVersion = serviceVersion; this.accountName = accountName; this.containerName = containerName; this.blobName = blobName; this.snapshot = snapshot; this.customerProvidedKey = customerProvidedKey; this.encryptionScope = encryptionScope; this.versionId = versionId; /* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer when the sas token has already been applied. */ try { URI.create(getBlobUrl()); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } } /** * Creates a new {@link BlobClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobClientBase} used to interact with the specific snapshot. */ public BlobClientBase getSnapshotClient(String snapshot) { return new BlobClientBase(this.client, getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey(), encryptionScope, getVersionId()); } /** * Creates a new {@link BlobClientBase} linked to the {@code version} of this blob resource. * * @param versionId the identifier for a specific version of this blob, * pass {@code null} to interact with the latest blob version. * @return a {@link BlobClientBase} used to interact with the specific version. */ public BlobClientBase getVersionClient(String versionId) { return new BlobClientBase(this.client, getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), getSnapshotId(), getCustomerProvidedKey(), encryptionScope, versionId); } /** * Creates a new {@link BlobClientBase} with the specified {@code encryptionScope}. * * @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope. * @return a {@link BlobClientBase} with the specified {@code encryptionScope}. */ public BlobClientBase getEncryptionScopeClient(String encryptionScope) { EncryptionScope finalEncryptionScope = null; if (encryptionScope != null) { finalEncryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return new BlobClientBase(this.client, getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey(), finalEncryptionScope, getVersionId()); } /** * Creates a new {@link BlobClientBase} with the specified {@code customerProvidedKey}. * * @param customerProvidedKey the {@link CustomerProvidedKey} for the blob, * pass {@code null} to use no customer provided key. * @return a {@link BlobClientBase} with the specified {@code customerProvidedKey}. */ public BlobClientBase getCustomerProvidedKeyClient(CustomerProvidedKey customerProvidedKey) { CpkInfo finalCustomerProvidedKey = null; if (customerProvidedKey != null) { finalCustomerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return new BlobClientBase(this.client, getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), snapshot, finalCustomerProvidedKey, encryptionScope, getVersionId()); } /** * Get the url of the storage account. * * @return the URL of the storage account */ public String getAccountUrl() { return azureBlobStorage.getUrl(); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public String getBlobUrl() { String blobUrl = azureBlobStorage.getUrl() + "/" + containerName + "/" + Utility.urlEncode(blobName); if (this.isSnapshot()) { blobUrl = Utility.appendQueryParameter(blobUrl, "snapshot", getSnapshotId()); } if (this.getVersionId() != null) { blobUrl = Utility.appendQueryParameter(blobUrl, "versionid", getVersionId()); } return blobUrl; } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return this.accountName; } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getContainerName --> * <pre> * String containerName = client.getContainerName& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getContainerName --> * * @return The name of the container. */ public final String getContainerName() { return this.containerName; } /** * Gets a client pointing to the parent container. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getContainerClient --> * <pre> * BlobContainerClient containerClient = client.getContainerClient& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getContainerClient --> * * @return {@link BlobContainerClient} */ public BlobContainerClient getContainerClient() { CustomerProvidedKey encryptionKey = this.customerProvidedKey == null ? null : new CustomerProvidedKey(this.customerProvidedKey.getEncryptionKey()); return new BlobContainerClientBuilder() .endpoint(this.getBlobUrl()) .pipeline(this.getHttpPipeline()) .serviceVersion(this.serviceVersion) .customerProvidedKey(encryptionKey) .encryptionScope(this.getEncryptionScope()).buildClient(); } /** * Decodes and gets the blob name. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getBlobName --> * <pre> * String blobName = client.getBlobName& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getBlobName --> * * @return The decoded name of the blob. */ public final String getBlobName() { return this.blobName; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return azureBlobStorage.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return this.customerProvidedKey; } /** * Gets the {@code encryption scope} used to encrypt this blob's content on the server. * * @return the encryption scope used for encryption. */ public String getEncryptionScope() { if (encryptionScope == null) { return null; } return encryptionScope.getEncryptionScope(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return this.serviceVersion; } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.snapshot; } /** * Gets the versionId for a blob resource * * @return A string that represents the versionId of the snapshot blob */ public String getVersionId() { return this.versionId; } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.snapshot != null; } /** * Opens a blob input stream to download the blob. * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream() { return openInputStream((BlobRange) null, null); } /** * Opens a blob input stream to download the specified range of the blob. * * @param range {@link BlobRange} * @param requestConditions An {@link BlobRequestConditions} object that represents the access conditions for the * blob. * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream(BlobRange range, BlobRequestConditions requestConditions) { return openInputStream(new BlobInputStreamOptions().setRange(range).setRequestConditions(requestConditions)); } /** * Opens a blob input stream to download the specified range of the blob. * * @param options {@link BlobInputStreamOptions} * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream(BlobInputStreamOptions options) { return openInputStream(options, null); } /** * Opens a blob input stream to download the specified range of the blob. * * @param options {@link BlobInputStreamOptions} * @param context {@link Context} * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream(BlobInputStreamOptions options, Context context) { Context contextFinal = context == null ? Context.NONE : context; options = options == null ? new BlobInputStreamOptions() : options; ConsistentReadControl consistentReadControl = options.getConsistentReadControl() == null ? ConsistentReadControl.ETAG : options.getConsistentReadControl(); BlobRequestConditions requestConditions = options.getRequestConditions() == null ? new BlobRequestConditions() : options.getRequestConditions(); BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); com.azure.storage.common.ParallelTransferOptions parallelTransferOptions = new com.azure.storage.common.ParallelTransferOptions().setBlockSizeLong((long) chunkSize); BiFunction<BlobRange, BlobRequestConditions, Mono<BlobDownloadAsyncResponse>> downloadFunc = (chunkRange, conditions) -> client.downloadStreamWithResponse(chunkRange, null, conditions, false, contextFinal); return ChunkedDownloadUtils.downloadFirstChunk(range, parallelTransferOptions, requestConditions, downloadFunc, true) .flatMap(tuple3 -> { BlobDownloadAsyncResponse downloadResponse = tuple3.getT3(); return FluxUtil.collectBytesInByteBufferStream(downloadResponse.getValue()) .map(ByteBuffer::wrap) .zipWith(Mono.just(downloadResponse)); }) .flatMap(tuple2 -> { ByteBuffer initialBuffer = tuple2.getT1(); BlobDownloadAsyncResponse downloadResponse = tuple2.getT2(); BlobProperties properties = ModelHelper.buildBlobPropertiesResponse(downloadResponse).getValue(); String eTag = properties.getETag(); String versionId = properties.getVersionId(); BlobClientBase client = this; switch (consistentReadControl) { case NONE: break; case ETAG: if (requestConditions.getIfMatch() == null) { requestConditions.setIfMatch(eTag); } break; case VERSION_ID: if (versionId == null) { return FluxUtil.monoError(LOGGER, new UnsupportedOperationException("Versioning is not supported on this account.")); } else { if (getVersionId() == null) { client = getVersionClient(versionId); } } break; default: return FluxUtil.monoError(LOGGER, new IllegalArgumentException("Concurrency control type not " + "supported.")); } return Mono.just(new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, initialBuffer, requestConditions, properties, contextFinal)); }).block(); } /** * Opens a seekable byte channel in read-only mode to download the blob. * * @param options {@link BlobSeekableByteChannelReadOptions} * @param context {@link Context} * @return A <code>SeekableByteChannel</code> that represents the channel to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobSeekableByteChannelReadResult openSeekableByteChannelRead( BlobSeekableByteChannelReadOptions options, Context context) { context = context == null ? Context.NONE : context; options = options == null ? new BlobSeekableByteChannelReadOptions() : options; ConsistentReadControl consistentReadControl = options.getConsistentReadControl() == null ? ConsistentReadControl.ETAG : options.getConsistentReadControl(); int chunkSize = options.getReadSizeInBytes() == null ? 4 * Constants.MB : options.getReadSizeInBytes(); long initialPosition = options.getInitialPosition() == null ? 0 : options.getInitialPosition(); ByteBuffer initialRange = ByteBuffer.allocate(chunkSize); BlobProperties properties; BlobDownloadResponse response; try (ByteBufferBackedOutputStream dstStream = new ByteBufferBackedOutputStream(initialRange)) { response = this.downloadStreamWithResponse(dstStream, new BlobRange(initialPosition, (long) initialRange.remaining()), null /*downloadRetryOptions*/, options.getRequestConditions(), false, null, context); properties = ModelHelper.buildBlobPropertiesResponse(response).getValue(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } initialRange.limit(initialRange.position()); initialRange.rewind(); BlobClientBase behaviorClient = this; BlobRequestConditions requestConditions = options.getRequestConditions(); switch (consistentReadControl) { case NONE: break; case ETAG: requestConditions = requestConditions != null ? requestConditions : new BlobRequestConditions(); if (requestConditions.getIfMatch() == null) { requestConditions.setIfMatch(properties.getETag()); } break; case VERSION_ID: if (properties.getVersionId() == null) { throw LOGGER.logExceptionAsError( new UnsupportedOperationException( "Version ID locking unsupported. Versioning is not supported on this account.")); } else { if (getVersionId() == null) { behaviorClient = this.getVersionClient(properties.getVersionId()); } } break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Concurrency control type " + consistentReadControl + " not supported.")); } StorageSeekableByteChannelBlobReadBehavior behavior = new StorageSeekableByteChannelBlobReadBehavior( behaviorClient, initialRange, initialPosition, properties.getBlobSize(), requestConditions); SeekableByteChannel channel = new StorageSeekableByteChannel(chunkSize, behavior, initialPosition); return new BlobSeekableByteChannelReadResult(channel, properties); } /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.exists --> * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.exists --> * * @return true if the blob exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Boolean exists() { return existsWithResponse(null, Context.NONE).getValue(); } /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return true if the blob exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Boolean> existsWithResponse(Duration timeout, Context context) { try { Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs() .getPropertiesNoCustomHeadersWithResponse(containerName, blobName, snapshot, versionId, null, null, null, null, null, null, null, null, customerProvidedKey, context); return new SimpleResponse<>(sendRequest(operation, timeout, BlobStorageException.class), true); } catch (RuntimeException e) { if (ModelHelper.checkBlobDoesNotExistStatusCode(e) && e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); } else { throw LOGGER.logExceptionAsError(e); } } } /** * Copies the data at the source URL to a blob. * <p> * This method triggers a long-running, asynchronous operations. The source may be another blob or an Azure File. If * the source is in another account, the source must either be public or authenticated with a SAS token. If the * source is in the same account, the Shared Key authorization on the destination will also be applied to the * source. The source URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.beginCopy * <pre> * final SyncPoller&lt;BlobCopyInfo, Void&gt; poller = client.beginCopy& * PollResponse&lt;BlobCopyInfo&gt; pollResponse = poller.poll& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.beginCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second * is used. * @return A {@link SyncPoller} to poll the progress of blob copy operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public SyncPoller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Duration pollInterval) { return beginCopy(sourceUrl, null, null, null, null, null, pollInterval); } /** * Copies the data at the source URL to a blob. * <p> * This method triggers a long-running, asynchronous operations. The source may be another blob or an Azure File. If * the source is in another account, the source must either be public or authenticated with a SAS token. If the * source is in the same account, the Shared Key authorization on the destination will also be applied to the * source. The source URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.beginCopy * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * RequestConditions modifiedRequestConditions = new RequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * SyncPoller&lt;BlobCopyInfo, Void&gt; poller = client.beginCopy& * RehydratePriority.STANDARD, modifiedRequestConditions, blobRequestConditions, Duration.ofSeconds& * * PollResponse&lt;BlobCopyInfo&gt; response = poller.waitUntil& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.beginCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. If there is leading or trailing whitespace in * any metadata key or value, it must be removed or encoded. * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedRequestConditions {@link RequestConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destRequestConditions {@link BlobRequestConditions} against the destination. * @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second * is used. * @return A {@link SyncPoller} to poll the progress of blob copy operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public SyncPoller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Map<String, String> metadata, AccessTier tier, RehydratePriority priority, RequestConditions sourceModifiedRequestConditions, BlobRequestConditions destRequestConditions, Duration pollInterval) { return this.beginCopy(new BlobBeginCopyOptions(sourceUrl).setMetadata(metadata).setTier(tier) .setRehydratePriority(priority).setSourceRequestConditions( ModelHelper.populateBlobSourceRequestConditions(sourceModifiedRequestConditions)) .setDestinationRequestConditions(destRequestConditions).setPollInterval(pollInterval)); } /** * Copies the data at the source URL to a blob. * <p> * This method triggers a long-running, asynchronous operations. The source may be another blob or an Azure File. If * the source is in another account, the source must either be public or authenticated with a SAS token. If the * source is in the same account, the Shared Key authorization on the destination will also be applied to the * source. The source URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.beginCopy * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Map&lt;String, String&gt; tags = Collections.singletonMap& * BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * SyncPoller&lt;BlobCopyInfo, Void&gt; poller = client.beginCopy& * .setTags& * .setSourceRequestConditions& * .setDestinationRequestConditions& * * PollResponse&lt;BlobCopyInfo&gt; response = poller.waitUntil& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.beginCopy * * <p>For more information, see the * <a href="https: * * @param options {@link BlobBeginCopyOptions} * @return A {@link SyncPoller} to poll the progress of blob copy operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public SyncPoller<BlobCopyInfo, Void> beginCopy(BlobBeginCopyOptions options) { StorageImplUtils.assertNotNull("options", options); final AtomicReference<String> copyId = new AtomicReference<>(); final Duration interval = options.getPollInterval() != null ? options.getPollInterval() : Duration.ofSeconds(1); final BlobBeginCopySourceRequestConditions sourceModifiedConditions = options.getSourceRequestConditions() == null ? new BlobBeginCopySourceRequestConditions() : options.getSourceRequestConditions(); final BlobRequestConditions destinationRequestConditions = options.getDestinationRequestConditions() == null ? new BlobRequestConditions() : options.getDestinationRequestConditions(); final BlobImmutabilityPolicy immutabilityPolicy = options.getImmutabilityPolicy() == null ? new BlobImmutabilityPolicy() : options.getImmutabilityPolicy(); Function<PollingContext<BlobCopyInfo>, PollResponse<BlobCopyInfo>> syncActivationOperation = (pollingContext) -> { try { new URL(options.getSourceUrl()); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'sourceUrl' is not a valid url.", ex)); } ResponseBase<BlobsStartCopyFromURLHeaders, Void> response = azureBlobStorage.getBlobs().startCopyFromURLWithResponse(containerName, blobName, options.getSourceUrl(), null, options.getMetadata(), options.getTier(), options.getRehydratePriority(), sourceModifiedConditions.getIfModifiedSince(), sourceModifiedConditions.getIfUnmodifiedSince(), sourceModifiedConditions.getIfMatch(), sourceModifiedConditions.getIfNoneMatch(), sourceModifiedConditions.getTagsConditions(), destinationRequestConditions.getIfModifiedSince(), destinationRequestConditions.getIfUnmodifiedSince(), destinationRequestConditions.getIfMatch(), destinationRequestConditions.getIfNoneMatch(), destinationRequestConditions.getTagsConditions(), destinationRequestConditions.getLeaseId(), null, ModelHelper.tagsToString(options.getTags()), options.isSealDestination(), immutabilityPolicy.getExpiryTime(), immutabilityPolicy.getPolicyMode(), options.isLegalHold(), Context.NONE); BlobsStartCopyFromURLHeaders headers = response.getDeserializedHeaders(); copyId.set(headers.getXMsCopyId()); return new PollResponse<>( LongRunningOperationStatus.IN_PROGRESS, new BlobCopyInfo(options.getSourceUrl(), headers.getXMsCopyId(), headers.getXMsCopyStatus(), headers.getETag(), headers.getLastModified(), ModelHelper.getErrorCode(response.getHeaders()), headers.getXMsVersionId()) ); }; Function<PollingContext<BlobCopyInfo>, PollResponse<BlobCopyInfo>> pollOperation = (pollingContext) -> onPoll(pollingContext.getLatestResponse(), destinationRequestConditions); BiFunction<PollingContext<BlobCopyInfo>, PollResponse<BlobCopyInfo>, BlobCopyInfo> cancelOperation = (pollingContext, firstResponse) -> { if (firstResponse == null || firstResponse.getValue() == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Cannot cancel a poll response that never started.")); } final String copyIdentifier = firstResponse.getValue().getCopyId(); if (!CoreUtils.isNullOrEmpty(copyIdentifier)) { LOGGER.info("Cancelling copy operation for copy id: {}", copyIdentifier); abortCopyFromUrl(copyIdentifier); return firstResponse.getValue(); } return null; }; Function<PollingContext<BlobCopyInfo>, Void> fetchResultOperation = (pollingContext) -> null; return SyncPoller.createPoller(interval, syncActivationOperation, pollOperation, cancelOperation, fetchResultOperation); } private PollResponse<BlobCopyInfo> onPoll(PollResponse<BlobCopyInfo> pollResponse, BlobRequestConditions requestConditions) { if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { return pollResponse; } final BlobCopyInfo lastInfo = pollResponse.getValue(); if (lastInfo == null) { LOGGER.warning("BlobCopyInfo does not exist. Activation operation failed."); return new PollResponse<>(LongRunningOperationStatus.fromString("COPY_START_FAILED", true), null); } try { Response<BlobProperties> response = getPropertiesWithResponse(requestConditions, null, null); BlobProperties value = response.getValue(); final CopyStatusType status = value.getCopyStatus(); final BlobCopyInfo result = new BlobCopyInfo(value.getCopySource(), value.getCopyId(), status, value.getETag(), value.getCopyCompletionTime(), value.getCopyStatusDescription(), value.getVersionId()); LongRunningOperationStatus operationStatus = ModelHelper.mapStatusToLongRunningOperationStatus(status); return new PollResponse<>(operationStatus, result); } catch (RuntimeException e) { return new PollResponse<>(LongRunningOperationStatus.fromString("POLLING_FAILED", true), lastInfo); } } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl * <pre> * client.abortCopyFromUrl& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. */ @ServiceMethod(returns = ReturnType.SINGLE) public void abortCopyFromUrl(String copyId) { abortCopyFromUrlWithResponse(copyId, null, null, Context.NONE); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse * <pre> * System.out.printf& * client.abortCopyFromUrlWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. * @param leaseId The lease ID the active lease on the blob must match. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> abortCopyFromUrlWithResponse(String copyId, String leaseId, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs().abortCopyFromURLNoCustomHeadersWithResponse(containerName, blobName, copyId, null, leaseId, null, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * <p> * The source must be a block blob no larger than 256MB. The source must also be either public or have a sas token * attached. The URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return The copy ID for the long running operation. * @throws IllegalArgumentException If {@code copySource} is a malformed {@link URL}. */ @ServiceMethod(returns = ReturnType.SINGLE) public String copyFromUrl(String copySource) { return copyFromUrlWithResponse(copySource, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * <p> * The source must be a block blob no larger than 256MB. The source must also be either public or have a sas token * attached. The URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * RequestConditions modifiedRequestConditions = new RequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * * System.out.printf& * client.copyFromUrlWithResponse& * blobRequestConditions, timeout, * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. If there is leading or trailing whitespace in * any metadata key or value, it must be removed or encoded. * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedRequestConditions {@link RequestConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destRequestConditions {@link BlobRequestConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. * @throws IllegalArgumentException If {@code copySource} is a malformed {@link URL}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<String> copyFromUrlWithResponse(String copySource, Map<String, String> metadata, AccessTier tier, RequestConditions sourceModifiedRequestConditions, BlobRequestConditions destRequestConditions, Duration timeout, Context context) { return this.copyFromUrlWithResponse(new BlobCopyFromUrlOptions(copySource).setMetadata(metadata) .setTier(tier).setSourceRequestConditions(sourceModifiedRequestConditions) .setDestinationRequestConditions(destRequestConditions), timeout, context); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * <p> * The source must be a block blob no larger than 256MB. The source must also be either public or have a sas token * attached. The URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Map&lt;String, String&gt; tags = Collections.singletonMap& * RequestConditions modifiedRequestConditions = new RequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * * System.out.printf& * client.copyFromUrlWithResponse& * .setTier& * .setDestinationRequestConditions& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobCopyFromUrlOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. * @throws IllegalArgumentException If {@code copySource} is a malformed {@link URL}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<String> copyFromUrlWithResponse(BlobCopyFromUrlOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); RequestConditions sourceModifiedRequestConditions = options.getSourceRequestConditions() == null ? new RequestConditions() : options.getSourceRequestConditions(); BlobRequestConditions destRequestConditions = options.getDestinationRequestConditions() == null ? new BlobRequestConditions() : options.getDestinationRequestConditions(); BlobImmutabilityPolicy immutabilityPolicy = options.getImmutabilityPolicy() == null ? new BlobImmutabilityPolicy() : options.getImmutabilityPolicy(); try { new URL(options.getCopySource()); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'copySource' is not a valid url.", ex)); } String sourceAuth = options.getSourceAuthorization() == null ? null : options.getSourceAuthorization().toString(); Callable<ResponseBase<BlobsCopyFromURLHeaders, Void>> operation = () -> this.azureBlobStorage.getBlobs().copyFromURLWithResponse(containerName, blobName, options.getCopySource(), null, options.getMetadata(), options.getTier(), sourceModifiedRequestConditions.getIfModifiedSince(), sourceModifiedRequestConditions.getIfUnmodifiedSince(), sourceModifiedRequestConditions.getIfMatch(), sourceModifiedRequestConditions.getIfNoneMatch(), destRequestConditions.getIfModifiedSince(), destRequestConditions.getIfUnmodifiedSince(), destRequestConditions.getIfMatch(), destRequestConditions.getIfNoneMatch(), destRequestConditions.getTagsConditions(), destRequestConditions.getLeaseId(), null, null, ModelHelper.tagsToString(options.getTags()), immutabilityPolicy.getExpiryTime(), immutabilityPolicy.getPolicyMode(), options.hasLegalHold(), sourceAuth, options.getCopySourceTagsMode(), this.encryptionScope, context); ResponseBase<BlobsCopyFromURLHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, response.getDeserializedHeaders().getXMsCopyId()); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.download * <pre> * client.download& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.download * * <p>For more information, see the * <a href="https: * * <p>This method will be deprecated in the future. Use {@link * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null * @deprecated use {@link */ @ServiceMethod(returns = ReturnType.SINGLE) @Deprecated public void download(OutputStream stream) { downloadStream(stream); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadStream * <pre> * client.downloadStream& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadStream * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null */ @ServiceMethod(returns = ReturnType.SINGLE) public void downloadStream(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * Downloads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobClient.downloadContent --> * <pre> * BinaryData data = client.downloadContent& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.BlobClient.downloadContent --> * * <p>For more information, see the * <a href="https: * * <p>This method supports downloads up to 2GB of data. Content will be buffered in memory. If the blob is larger, * use {@link * * @return The content of the blob. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public BinaryData downloadContent() { return blockWithOptionalTimeout(client.downloadContent(), null); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * <pre> * BlobRange range = new BlobRange& * DownloadRetryOptions options = new DownloadRetryOptions& * * System.out.printf& * client.downloadWithResponse& * timeout, new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * <p>This method will be deprecated in the future. * Use {@link * BlobRequestConditions, boolean, Duration, Context)} instead. * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null * @deprecated use {@link */ @ServiceMethod(returns = ReturnType.SINGLE) @Deprecated public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { return downloadStreamWithResponse(stream, range, options, requestConditions, getRangeContentMd5, timeout, context); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse * <pre> * BlobRange range = new BlobRange& * DownloadRetryOptions options = new DownloadRetryOptions& * * System.out.printf& * client.downloadStreamWithResponse& * timeout, new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobDownloadResponse downloadStreamWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadStreamWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> FluxUtil.writeToOutputStream(response.getValue(), stream) .thenReturn(new BlobDownloadResponse(response))); return blockWithOptionalTimeout(download, timeout); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * <pre> * DownloadRetryOptions options = new DownloadRetryOptions& * * BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse& * timeout, new Context& * BinaryData content = contentResponse.getValue& * System.out.printf& * contentResponse.getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * * <p>For more information, see the * <a href="https: * * <p>This method supports downloads up to 2GB of data. Content will be buffered in memory. If the blob is larger, * use {@link * DownloadRetryOptions, BlobRequestConditions, boolean, Duration, Context)} to download larger blobs.</p> * * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobDownloadContentResponse downloadContentWithResponse( DownloadRetryOptions options, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<BlobDownloadContentResponse> download = client .downloadStreamWithResponse(null, options, requestConditions, false, context) .flatMap(r -> BinaryData.fromFlux(r.getValue()) .map(data -> new BlobDownloadContentAsyncResponse( r.getRequest(), r.getStatusCode(), r.getHeaders(), data, r.getDeserializedHeaders()) )) .map(BlobDownloadContentResponse::new); return blockWithOptionalTimeout(download, timeout); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * <pre> * DownloadRetryOptions options = new DownloadRetryOptions& * BlobRange range = new BlobRange& * * BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse& * range, false, timeout, new Context& * BinaryData content = contentResponse.getValue& * System.out.printf& * contentResponse.getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * * <p>For more information, see the * <a href="https: * * <p>This method supports downloads up to 2GB of data. Content will be buffered in memory. If the blob is larger, * use {@link * DownloadRetryOptions, BlobRequestConditions, boolean, Duration, Context)} to download larger blobs.</p> * * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param range {@link BlobRange} * @param getRangeContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobDownloadContentResponse downloadContentWithResponse(DownloadRetryOptions options, BlobRequestConditions requestConditions, BlobRange range, boolean getRangeContentMd5, Duration timeout, Context context) { Mono<BlobDownloadContentResponse> download = client .downloadStreamWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(r -> BinaryData.fromFlux(r.getValue()) .map(data -> new BlobDownloadContentAsyncResponse( r.getRequest(), r.getStatusCode(), r.getHeaders(), data, r.getDeserializedHeaders()) )) .map(BlobDownloadContentResponse::new); return blockWithOptionalTimeout(download, timeout); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * <pre> * client.downloadToFile& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobProperties downloadToFile(String filePath) { return downloadToFile(filePath, false); } /** * Downloads the entire blob into a file specified by the path. * * <p>If overwrite is set to false, the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * <pre> * boolean overwrite = false; & * client.downloadToFile& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param overwrite Whether to overwrite the file, should the file exist. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobProperties downloadToFile(String filePath, boolean overwrite) { Set<OpenOption> openOptions = null; if (overwrite) { openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.CREATE); openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); openOptions.add(StandardOpenOption.READ); openOptions.add(StandardOpenOption.WRITE); } return downloadToFileWithResponse(filePath, null, null, null, null, false, openOptions, null, Context.NONE) .getValue(); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * <pre> * BlobRange range = new BlobRange& * DownloadRetryOptions options = new DownloadRetryOptions& * * client.downloadToFileWithResponse& * options, null, false, timeout, new Context& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link BlobRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param downloadRetryOptions {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Duration timeout, Context context) { return downloadToFileWithResponse(filePath, range, parallelTransferOptions, downloadRetryOptions, requestConditions, rangeGetContentMd5, null, timeout, context); } /** * Downloads the entire blob into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * <pre> * BlobRange blobRange = new BlobRange& * DownloadRetryOptions downloadRetryOptions = new DownloadRetryOptions& * Set&lt;OpenOption&gt; openOptions = new HashSet&lt;&gt;& * StandardOpenOption.WRITE, StandardOpenOption.READ& * * client.downloadToFileWithResponse& * downloadRetryOptions, null, false, openOptions, timeout, new Context& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link BlobRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param downloadRetryOptions {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Set<OpenOption> openOptions, Duration timeout, Context context) { final com.azure.storage.common.ParallelTransferOptions finalParallelTransferOptions = ModelHelper.wrapBlobOptions(ModelHelper.populateAndApplyDefaults(parallelTransferOptions)); return downloadToFileWithResponse(new BlobDownloadToFileOptions(filePath).setRange(range) .setParallelTransferOptions(finalParallelTransferOptions) .setDownloadRetryOptions(downloadRetryOptions).setRequestConditions(requestConditions) .setRetrieveContentRangeMd5(rangeGetContentMd5).setOpenOptions(openOptions), timeout, context); } /** * Downloads the entire blob into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * <pre> * client.downloadToFileWithResponse& * .setRange& * .setDownloadRetryOptions& * .setOpenOptions& * StandardOpenOption.READ& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobDownloadToFileOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> downloadToFileWithResponse(BlobDownloadToFileOptions options, Duration timeout, Context context) { Mono<Response<BlobProperties>> download = client.downloadToFileWithResponse(options, context); return blockWithOptionalTimeout(download, timeout); } /** * Deletes the specified blob or snapshot. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.delete --> * <pre> * client.delete& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.delete --> * * <p>For more information, see the * <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * <pre> * System.out.printf& * client.deleteWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Callable<Response<Void>> operation = () -> azureBlobStorage.getBlobs().deleteNoCustomHeadersWithResponse( containerName, blobName, snapshot, versionId, null, finalRequestConditions.getLeaseId(), deleteBlobSnapshotOptions, finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, null, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Deletes the specified blob or snapshot if it exists. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists --> * <pre> * boolean result = client.deleteIfExists& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists --> * * <p>For more information, see the * <a href="https: * @return {@code true} if delete succeeds, or {@code false} if blob does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public boolean deleteIfExists() { return deleteIfExistsWithResponse(null, null, null, Context.NONE).getValue(); } /** * Deletes the specified blob or snapshot if it exists. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse * <pre> * Response&lt;Boolean&gt; response = client.deleteIfExistsWithResponse& * new Context& * if & * System.out.println& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. If {@link Response}'s status code is 202, the base * blob was successfully deleted. If status code is 404, the base blob does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Boolean> deleteIfExistsWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { try { Response<Void> response = this.deleteWithResponse(deleteBlobSnapshotOptions, requestConditions, timeout, context); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), true); } catch (RuntimeException e) { if (ModelHelper.checkBlobDoesNotExistStatusCode(e) && e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); } else { throw LOGGER.logExceptionAsError(e); } } } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getProperties --> * <pre> * BlobProperties properties = client.getProperties& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getProperties --> * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * <pre> * BlobRequestConditions requestConditions = new BlobRequestConditions& * * BlobProperties properties = client.getPropertiesWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> getPropertiesWithResponse(BlobRequestConditions requestConditions, Duration timeout, Context context) { BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsGetPropertiesHeaders, Void>> operation = () -> this.azureBlobStorage.getBlobs().getPropertiesWithResponse(containerName, blobName, snapshot, versionId, null, finalRequestConditions.getLeaseId(), finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, customerProvidedKey, finalContext); ResponseBase<BlobsGetPropertiesHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, BlobPropertiesConstructorProxy .create(new BlobPropertiesInternalGetProperties(response.getDeserializedHeaders()))); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * <pre> * client.setHttpHeaders& * .setContentLanguage& * .setContentType& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} */ @ServiceMethod(returns = ReturnType.SINGLE) public void setHttpHeaders(BlobHttpHeaders headers) { setHttpHeadersWithResponse(headers, null, null, Context.NONE); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse * <pre> * BlobRequestConditions requestConditions = new BlobRequestConditions& * * System.out.printf& * client.setHttpHeadersWithResponse& * .setContentLanguage& * .setContentType& * .getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobRequestConditions requestConditions, Duration timeout, Context context) { BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs().setHttpHeadersNoCustomHeadersWithResponse(containerName, blobName, null, finalRequestConditions.getLeaseId(), finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, headers, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setMetadata * <pre> * client.setMetadata& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setMetadata(Map<String, String> metadata) { setMetadataWithResponse(metadata, null, null, Context.NONE); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * <pre> * BlobRequestConditions requestConditions = new BlobRequestConditions& * * System.out.printf& * client.setMetadataWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setMetadataWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs().setMetadataNoCustomHeadersWithResponse(containerName, blobName, null, metadata, finalRequestConditions.getLeaseId(), finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, customerProvidedKey, encryptionScope, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getTags --> * <pre> * Map&lt;String, String&gt; tags = client.getTags& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getTags --> * * <p>For more information, see the * <a href="https: * * @return The blob's tags. */ @ServiceMethod(returns = ReturnType.SINGLE) public Map<String, String> getTags() { return this.getTagsWithResponse(new BlobGetTagsOptions(), null, Context.NONE).getValue(); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse * <pre> * Map&lt;String, String&gt; tags = client.getTagsWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobGetTagsOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob's tags. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Map<String, String>> getTagsWithResponse(BlobGetTagsOptions options, Duration timeout, Context context) { BlobGetTagsOptions finalTagOptions = (options == null) ? new BlobGetTagsOptions() : options; BlobRequestConditions requestConditions = (finalTagOptions.getRequestConditions() == null) ? new BlobRequestConditions() : finalTagOptions.getRequestConditions(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsGetTagsHeaders, BlobTags>> operation = () -> this.azureBlobStorage.getBlobs().getTagsWithResponse(containerName, blobName, null, null, snapshot, versionId, requestConditions.getTagsConditions(), requestConditions.getLeaseId(), finalContext); ResponseBase<BlobsGetTagsHeaders, BlobTags> response = sendRequest(operation, timeout, BlobStorageException.class); Map<String, String> tags = new HashMap<>(); for (BlobTag tag : response.getValue().getBlobTagSet()) { tags.put(tag.getKey(), tag.getValue()); } return new SimpleResponse<>(response, tags); } /** * Sets user defined tags. The specified tags in this method will replace existing tags. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setTags * <pre> * client.setTags& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setTags * * <p>For more information, see the * <a href="https: * * @param tags Tags to associate with the blob. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setTags(Map<String, String> tags) { this.setTagsWithResponse(new BlobSetTagsOptions(tags), null, Context.NONE); } /** * Sets user defined tags. The specified tags in this method will replace existing tags. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse * <pre> * System.out.printf& * client.setTagsWithResponse& * new Context& * .getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobSetTagsOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setTagsWithResponse(BlobSetTagsOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions requestConditions = (options.getRequestConditions() == null) ? new BlobRequestConditions() : options.getRequestConditions(); List<BlobTag> tagList = null; if (options.getTags() != null) { tagList = new ArrayList<>(); for (Map.Entry<String, String> entry : options.getTags().entrySet()) { tagList.add(new BlobTag().setKey(entry.getKey()).setValue(entry.getValue())); } } BlobTags t = new BlobTags().setBlobTagSet(tagList); Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs().setTagsNoCustomHeadersWithResponse(containerName, blobName, null, versionId, null, null, null, requestConditions.getTagsConditions(), requestConditions.getLeaseId(), t, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.createSnapshot --> * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.createSnapshot --> * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobClientBase} which is used to interact with the created snapshot, use * {@link BlobClientBase */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobClientBase createSnapshot() { return createSnapshotWithResponse(null, null, null, Context.NONE).getValue(); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * <pre> * Map&lt;String, String&gt; snapshotMetadata = Collections.singletonMap& * BlobRequestConditions requestConditions = new BlobRequestConditions& * * System.out.printf& * client.createSnapshotWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing a {@link BlobClientBase} which is used to interact with the created snapshot, use * {@link BlobClientBase */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobClientBase> createSnapshotWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Callable<ResponseBase<BlobsCreateSnapshotHeaders, Void>> operation = () -> this.azureBlobStorage.getBlobs() .createSnapshotWithResponse(containerName, blobName, null, metadata, finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), finalRequestConditions.getLeaseId(), null, customerProvidedKey, encryptionScope, finalContext); ResponseBase<BlobsCreateSnapshotHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, this.getSnapshotClient(response.getDeserializedHeaders().getXMsSnapshot())); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * <pre> * client.setAccessTier& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setAccessTier(AccessTier tier) { setAccessTierWithResponse(tier, null, null, null, Context.NONE); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * <pre> * System.out.printf& * client.setAccessTierWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseId The lease ID the active lease on the blob must match. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority, String leaseId, Duration timeout, Context context) { return setAccessTierWithResponse(new BlobSetAccessTierOptions(tier).setPriority(priority).setLeaseId(leaseId), timeout, context); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * <pre> * System.out.printf& * client.setAccessTierWithResponse& * .setPriority& * .setLeaseId& * .setTagsConditions& * timeout, new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobSetAccessTierOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setAccessTierWithResponse(BlobSetAccessTierOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs().setTierNoCustomHeadersWithResponse( containerName, blobName, options.getTier(), snapshot, versionId, null, options.getPriority(), null, options.getLeaseId(), options.getTagsConditions(), finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.undelete --> * <pre> * client.undelete& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.undelete --> * * <p>For more information, see the * <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public void undelete() { undeleteWithResponse(null, Context.NONE); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * <pre> * System.out.printf& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs().undeleteNoCustomHeadersWithResponse( containerName, blobName, null, null, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo --> * <pre> * StorageAccountInfo accountInfo = client.getAccountInfo& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo --> * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ @ServiceMethod(returns = ReturnType.SINGLE) public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * <pre> * StorageAccountInfo accountInfo = client.getAccountInfoWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The sku name and account kind. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsGetAccountInfoHeaders, Void>> operation = () -> this.azureBlobStorage.getBlobs() .getAccountInfoWithResponse(containerName, blobName, finalContext); ResponseBase<BlobsGetAccountInfoHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); BlobsGetAccountInfoHeaders hd = response.getDeserializedHeaders(); return new SimpleResponse<>(response, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind())); } /** * Generates a user delegation SAS for the blob using the specified {@link BlobServiceSasSignatureValues}. * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a user delegation SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * BlobSasPermission myPermission = new BlobSasPermission& * * BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link BlobServiceClient * how to get a user delegation key. * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey, getAccountName(), Context.NONE); } /** * Generates a user delegation SAS for the blob using the specified {@link BlobServiceSasSignatureValues}. * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a user delegation SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * BlobSasPermission myPermission = new BlobSasPermission& * * BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link BlobServiceClient * how to get a user delegation key. * @param accountName The account name. * @param context Additional context that is passed through the code when generating a SAS. * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey, String accountName, Context context) { return new BlobSasImplUtil(blobServiceSasSignatureValues, getContainerName(), getBlobName(), getSnapshotId(), getVersionId(), getEncryptionScope()).generateUserDelegationSas(userDelegationKey, accountName, context); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * BlobSasPermission permission = new BlobSasPermission& * * BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues& * .setStartTime& * * client.generateSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues) { return generateSas(blobServiceSasSignatureValues, Context.NONE); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * BlobSasPermission permission = new BlobSasPermission& * * BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues& * .setStartTime& * * & * client.generateSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, Context context) { return new BlobSasImplUtil(blobServiceSasSignatureValues, getContainerName(), getBlobName(), getSnapshotId(), getVersionId(), getEncryptionScope()).generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * <pre> * String expression = &quot;SELECT * from BlobStorage&quot;; * InputStream inputStream = client.openQueryInputStream& * & * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * * @param expression The query expression. * @return An <code>InputStream</code> object that represents the stream to use for reading the query response. */ @ServiceMethod(returns = ReturnType.SINGLE) public InputStream openQueryInputStream(String expression) { return openQueryInputStreamWithResponse(new BlobQueryOptions(expression)).getValue(); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * <pre> * String expression = &quot;SELECT * from BlobStorage&quot;; * BlobQuerySerialization input = new BlobQueryDelimitedSerialization& * .setColumnSeparator& * .setEscapeChar& * .setRecordSeparator& * .setHeadersPresent& * .setFieldQuote& * BlobQuerySerialization output = new BlobQueryJsonSerialization& * .setRecordSeparator& * BlobRequestConditions requestConditions = new BlobRequestConditions& * .setLeaseId& * Consumer&lt;BlobQueryError&gt; errorConsumer = System.out::println; * Consumer&lt;BlobQueryProgress&gt; progressConsumer = progress -&gt; System.out.println& * + progress.getBytesScanned& * BlobQueryOptions queryOptions = new BlobQueryOptions& * .setInputSerialization& * .setOutputSerialization& * .setRequestConditions& * .setErrorConsumer& * .setProgressConsumer& * * InputStream inputStream = client.openQueryInputStreamWithResponse& * & * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * * @param queryOptions {@link BlobQueryOptions The query options}. * @return A response containing status code and HTTP headers including an <code>InputStream</code> object * that represents the stream to use for reading the query response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<InputStream> openQueryInputStreamWithResponse(BlobQueryOptions queryOptions) { StorageImplUtils.assertNotNull("options", queryOptions); BlobRequestConditions requestConditions = queryOptions.getRequestConditions() == null ? new BlobRequestConditions() : queryOptions.getRequestConditions(); QuerySerialization in = BlobQueryReader.transformInputSerialization(queryOptions.getInputSerialization(), LOGGER); QuerySerialization out = BlobQueryReader.transformOutputSerialization(queryOptions.getOutputSerialization(), LOGGER); QueryRequest qr = new QueryRequest() .setExpression(queryOptions.getExpression()) .setInputSerialization(in) .setOutputSerialization(out); ResponseBase<BlobsQueryHeaders, InputStream> response = this.azureBlobStorage.getBlobs().queryWithResponse( containerName, blobName, getSnapshotId(), null, requestConditions.getLeaseId(), requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null, qr, getCustomerProvidedKey(), Context.NONE); InputStream avroInputStream = response.getValue(); BlobQueryReader reader = new BlobQueryReader(null, queryOptions.getProgressConsumer(), queryOptions.getErrorConsumer()); try { InputStream resultStream = reader.readInputStream(avroInputStream); return new SimpleResponse<>(response, resultStream); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.query * <pre> * ByteArrayOutputStream queryData = new ByteArrayOutputStream& * String expression = &quot;SELECT * from BlobStorage&quot;; * client.query& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.query * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param expression The query expression. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public void query(OutputStream stream, String expression) { queryWithResponse(new BlobQueryOptions(expression, stream), null, Context.NONE); } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse * <pre> * ByteArrayOutputStream queryData = new ByteArrayOutputStream& * String expression = &quot;SELECT * from BlobStorage&quot;; * BlobQueryJsonSerialization input = new BlobQueryJsonSerialization& * .setRecordSeparator& * BlobQueryDelimitedSerialization output = new BlobQueryDelimitedSerialization& * .setEscapeChar& * .setColumnSeparator& * .setRecordSeparator& * .setFieldQuote& * .setHeadersPresent& * BlobRequestConditions requestConditions = new BlobRequestConditions& * Consumer&lt;BlobQueryError&gt; errorConsumer = System.out::println; * Consumer&lt;BlobQueryProgress&gt; progressConsumer = progress -&gt; System.out.println& * + progress.getBytesScanned& * BlobQueryOptions queryOptions = new BlobQueryOptions& * .setInputSerialization& * .setOutputSerialization& * .setRequestConditions& * .setErrorConsumer& * .setProgressConsumer& * System.out.printf& * client.queryWithResponse& * .getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse * * @param queryOptions {@link BlobQueryOptions The query options}. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Sets the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy * <pre> * BlobImmutabilityPolicy policy = new BlobImmutabilityPolicy& * .setPolicyMode& * .setExpiryTime& * BlobImmutabilityPolicy setPolicy = client.setImmutabilityPolicy& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy * * @param immutabilityPolicy {@link BlobImmutabilityPolicy The immutability policy}. * @return The immutability policy. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobImmutabilityPolicy setImmutabilityPolicy(BlobImmutabilityPolicy immutabilityPolicy) { return setImmutabilityPolicyWithResponse(immutabilityPolicy, null, null, Context.NONE).getValue(); } /** * Sets the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse * <pre> * BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy& * .setPolicyMode& * .setExpiryTime& * BlobRequestConditions requestConditions = new BlobRequestConditions& * .setIfUnmodifiedSince& * Response&lt;BlobImmutabilityPolicy&gt; response = client.setImmutabilityPolicyWithResponse& * requestConditions, timeout, new Context& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse * * @param immutabilityPolicy {@link BlobImmutabilityPolicy The immutability policy}. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the immutability policy. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobImmutabilityPolicy> setImmutabilityPolicyWithResponse(BlobImmutabilityPolicy immutabilityPolicy, BlobRequestConditions requestConditions, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; BlobImmutabilityPolicy finalImmutabilityPolicy = immutabilityPolicy == null ? new BlobImmutabilityPolicy() : immutabilityPolicy; if (BlobImmutabilityPolicyMode.MUTABLE.equals(finalImmutabilityPolicy.getPolicyMode())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("immutabilityPolicy.policyMode must be %s or %s", BlobImmutabilityPolicyMode.LOCKED.toString(), BlobImmutabilityPolicyMode.UNLOCKED.toString()))); } BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; ModelHelper.validateConditionsNotPresent(finalRequestConditions, EnumSet.of(BlobRequestConditionProperty.LEASE_ID, BlobRequestConditionProperty.TAGS_CONDITIONS, BlobRequestConditionProperty.IF_MATCH, BlobRequestConditionProperty.IF_NONE_MATCH, BlobRequestConditionProperty.IF_MODIFIED_SINCE), "setImmutabilityPolicy(WithResponse)", "requestConditions"); Callable<ResponseBase<BlobsSetImmutabilityPolicyHeaders, Void>> operation = () -> this.azureBlobStorage.getBlobs().setImmutabilityPolicyWithResponse(containerName, blobName, null, null, finalRequestConditions.getIfUnmodifiedSince(), finalImmutabilityPolicy.getExpiryTime(), finalImmutabilityPolicy.getPolicyMode(), finalContext); ResponseBase<BlobsSetImmutabilityPolicyHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); BlobsSetImmutabilityPolicyHeaders headers = response.getDeserializedHeaders(); BlobImmutabilityPolicy responsePolicy = new BlobImmutabilityPolicy() .setPolicyMode(headers.getXMsImmutabilityPolicyMode()) .setExpiryTime(headers.getXMsImmutabilityPolicyUntilDate()); return new SimpleResponse<>(response, responsePolicy); } /** * Delete the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy --> * <pre> * client.deleteImmutabilityPolicy& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy --> * */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteImmutabilityPolicy() { deleteImmutabilityPolicyWithResponse(null, Context.NONE).getValue(); } /** * Delete the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse * <pre> * System.out.println& * + client.deleteImmutabilityPolicyWithResponse& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the immutability policy. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteImmutabilityPolicyWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = () -> this.azureBlobStorage.getBlobs() .deleteImmutabilityPolicyNoCustomHeadersWithResponse(containerName, blobName, null, null, finalContext); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Sets a legal hold on the blob. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setLegalHold * <pre> * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setLegalHold * * @param legalHold Whether you want a legal hold on the blob. * @return The legal hold result. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobLegalHoldResult setLegalHold(boolean legalHold) { return setLegalHoldWithResponse(legalHold, null, Context.NONE).getValue(); } /** * Sets a legal hold on the blob. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse * <pre> * System.out.println& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse * * @param legalHold Whether you want a legal hold on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the legal hold result. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobLegalHoldResult> setLegalHoldWithResponse(boolean legalHold, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsSetLegalHoldHeaders, Void>> operation = () -> this.azureBlobStorage.getBlobs().setLegalHoldWithResponse(containerName, blobName, legalHold, null, null, finalContext); ResponseBase<BlobsSetLegalHoldHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, new InternalBlobLegalHoldResult(response.getDeserializedHeaders().isXMsLegalHold())); } }
class BlobClientBase { private static final ClientLogger LOGGER = new ClientLogger(BlobClientBase.class); private static final Set<OpenOption> DEFAULT_OPEN_OPTIONS_SET = Collections.unmodifiableSet(new HashSet<>( Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE))); /** * Backing REST client for the blob client. */ protected final AzureBlobStorageImpl azureBlobStorage; private final String snapshot; private final String versionId; private final CpkInfo customerProvidedKey; /** * Encryption scope of the blob. */ protected final EncryptionScope encryptionScope; /** * Storage account name that contains the blob. */ protected final String accountName; /** * Container name that contains the blob. */ protected final String containerName; /** * Name of the blob. */ protected final String blobName; /** * Storage REST API version used in requests to the Storage service. */ protected final BlobServiceVersion serviceVersion; private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { if (client.getSnapshotId() != null && client.getVersionId() != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.client = client; this.azureBlobStorage = new AzureBlobStorageImplBuilder() .pipeline(client.getHttpPipeline()) .url(client.getAccountUrl()) .version(client.getServiceVersion().getVersion()) .buildClient(); this.serviceVersion = client.getServiceVersion(); this.accountName = client.getAccountName(); this.containerName = client.getContainerName(); this.blobName = client.getBlobName(); this.snapshot = client.getSnapshotId(); this.customerProvidedKey = client.getCustomerProvidedKey(); this.encryptionScope = new EncryptionScope().setEncryptionScope(client.getEncryptionScope()); this.versionId = client.getVersionId(); /* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer when the sas token has already been applied. */ try { URI.create(getBlobUrl()); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } } /** * Protected constructor for use by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param containerName The container name. * @param blobName The blob name. * @param snapshot The snapshot identifier for the blob, pass {@code null} to interact with the blob directly. * @param customerProvidedKey Customer provided key used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param encryptionScope Encryption scope used during encryption of the blob's data on the server, pass * {@code null} to allow the service to use its own encryption. * @param versionId The version identifier for the blob, pass {@code null} to interact with the latest blob version. */ protected BlobClientBase(BlobAsyncClientBase client, HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey, EncryptionScope encryptionScope, String versionId) { if (snapshot != null && versionId != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.client = client; this.azureBlobStorage = new AzureBlobStorageImplBuilder() .pipeline(pipeline) .url(url) .version(serviceVersion.getVersion()) .buildClient(); this.serviceVersion = serviceVersion; this.accountName = accountName; this.containerName = containerName; this.blobName = blobName; this.snapshot = snapshot; this.customerProvidedKey = customerProvidedKey; this.encryptionScope = encryptionScope; this.versionId = versionId; /* Check to make sure the uri is valid. We don't want the error to occur later in the generated layer when the sas token has already been applied. */ try { URI.create(getBlobUrl()); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } } /** * Creates a new {@link BlobClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobClientBase} used to interact with the specific snapshot. */ public BlobClientBase getSnapshotClient(String snapshot) { return new BlobClientBase(this.client.getSnapshotClient(snapshot), getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey(), encryptionScope, getVersionId()); } /** * Creates a new {@link BlobClientBase} linked to the {@code version} of this blob resource. * * @param versionId the identifier for a specific version of this blob, * pass {@code null} to interact with the latest blob version. * @return a {@link BlobClientBase} used to interact with the specific version. */ public BlobClientBase getVersionClient(String versionId) { return new BlobClientBase(this.client.getVersionClient(versionId), getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), getSnapshotId(), getCustomerProvidedKey(), encryptionScope, versionId); } /** * Creates a new {@link BlobClientBase} with the specified {@code encryptionScope}. * * @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope. * @return a {@link BlobClientBase} with the specified {@code encryptionScope}. */ public BlobClientBase getEncryptionScopeClient(String encryptionScope) { EncryptionScope finalEncryptionScope = null; if (encryptionScope != null) { finalEncryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return new BlobClientBase(this.client.getEncryptionScopeAsyncClient(encryptionScope), getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), snapshot, getCustomerProvidedKey(), finalEncryptionScope, getVersionId()); } /** * Creates a new {@link BlobClientBase} with the specified {@code customerProvidedKey}. * * @param customerProvidedKey the {@link CustomerProvidedKey} for the blob, * pass {@code null} to use no customer provided key. * @return a {@link BlobClientBase} with the specified {@code customerProvidedKey}. */ public BlobClientBase getCustomerProvidedKeyClient(CustomerProvidedKey customerProvidedKey) { CpkInfo finalCustomerProvidedKey = null; if (customerProvidedKey != null) { finalCustomerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return new BlobClientBase(this.client.getCustomerProvidedKeyAsyncClient(customerProvidedKey), getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getContainerName(), getBlobName(), snapshot, finalCustomerProvidedKey, encryptionScope, getVersionId()); } /** * Get the url of the storage account. * * @return the URL of the storage account */ public String getAccountUrl() { return azureBlobStorage.getUrl(); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public String getBlobUrl() { String blobUrl = azureBlobStorage.getUrl() + "/" + containerName + "/" + Utility.urlEncode(blobName); if (this.isSnapshot()) { blobUrl = Utility.appendQueryParameter(blobUrl, "snapshot", getSnapshotId()); } if (this.getVersionId() != null) { blobUrl = Utility.appendQueryParameter(blobUrl, "versionid", getVersionId()); } return blobUrl; } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return this.accountName; } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getContainerName --> * <pre> * String containerName = client.getContainerName& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getContainerName --> * * @return The name of the container. */ public final String getContainerName() { return this.containerName; } /** * Gets a client pointing to the parent container. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getContainerClient --> * <pre> * BlobContainerClient containerClient = client.getContainerClient& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getContainerClient --> * * @return {@link BlobContainerClient} */ public BlobContainerClient getContainerClient() { CustomerProvidedKey encryptionKey = this.customerProvidedKey == null ? null : new CustomerProvidedKey(this.customerProvidedKey.getEncryptionKey()); return new BlobContainerClientBuilder() .endpoint(this.getBlobUrl()) .pipeline(this.getHttpPipeline()) .serviceVersion(this.serviceVersion) .customerProvidedKey(encryptionKey) .encryptionScope(this.getEncryptionScope()).buildClient(); } /** * Decodes and gets the blob name. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getBlobName --> * <pre> * String blobName = client.getBlobName& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getBlobName --> * * @return The decoded name of the blob. */ public final String getBlobName() { return this.blobName; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return azureBlobStorage.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return this.customerProvidedKey; } /** * Gets the {@code encryption scope} used to encrypt this blob's content on the server. * * @return the encryption scope used for encryption. */ public String getEncryptionScope() { if (encryptionScope == null) { return null; } return encryptionScope.getEncryptionScope(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return this.serviceVersion; } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.snapshot; } /** * Gets the versionId for a blob resource * * @return A string that represents the versionId of the snapshot blob */ public String getVersionId() { return this.versionId; } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.snapshot != null; } /** * Opens a blob input stream to download the blob. * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream() { return openInputStream((BlobRange) null, null); } /** * Opens a blob input stream to download the specified range of the blob. * * @param range {@link BlobRange} * @param requestConditions An {@link BlobRequestConditions} object that represents the access conditions for the * blob. * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream(BlobRange range, BlobRequestConditions requestConditions) { return openInputStream(new BlobInputStreamOptions().setRange(range).setRequestConditions(requestConditions)); } /** * Opens a blob input stream to download the specified range of the blob. * * @param options {@link BlobInputStreamOptions} * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream(BlobInputStreamOptions options) { return openInputStream(options, null); } /** * Opens a blob input stream to download the specified range of the blob. * * @param options {@link BlobInputStreamOptions} * @param context {@link Context} * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobInputStream openInputStream(BlobInputStreamOptions options, Context context) { Context contextFinal = context == null ? Context.NONE : context; options = options == null ? new BlobInputStreamOptions() : options; ConsistentReadControl consistentReadControl = options.getConsistentReadControl() == null ? ConsistentReadControl.ETAG : options.getConsistentReadControl(); BlobRequestConditions requestConditions = options.getRequestConditions() == null ? new BlobRequestConditions() : options.getRequestConditions(); BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); com.azure.storage.common.ParallelTransferOptions parallelTransferOptions = new com.azure.storage.common.ParallelTransferOptions().setBlockSizeLong((long) chunkSize); BiFunction<BlobRange, BlobRequestConditions, Mono<BlobDownloadAsyncResponse>> downloadFunc = (chunkRange, conditions) -> client.downloadStreamWithResponse(chunkRange, null, conditions, false, contextFinal); return ChunkedDownloadUtils.downloadFirstChunk(range, parallelTransferOptions, requestConditions, downloadFunc, true) .flatMap(tuple3 -> { BlobDownloadAsyncResponse downloadResponse = tuple3.getT3(); return FluxUtil.collectBytesInByteBufferStream(downloadResponse.getValue()) .map(ByteBuffer::wrap) .zipWith(Mono.just(downloadResponse)); }) .flatMap(tuple2 -> { ByteBuffer initialBuffer = tuple2.getT1(); BlobDownloadAsyncResponse downloadResponse = tuple2.getT2(); BlobProperties properties = ModelHelper.buildBlobPropertiesResponse(downloadResponse).getValue(); String eTag = properties.getETag(); String versionId = properties.getVersionId(); BlobClientBase client = this; switch (consistentReadControl) { case NONE: break; case ETAG: if (requestConditions.getIfMatch() == null) { requestConditions.setIfMatch(eTag); } break; case VERSION_ID: if (versionId == null) { return FluxUtil.monoError(LOGGER, new UnsupportedOperationException("Versioning is not supported on this account.")); } else { if (getVersionId() == null) { client = getVersionClient(versionId); } } break; default: return FluxUtil.monoError(LOGGER, new IllegalArgumentException("Concurrency control type not " + "supported.")); } return Mono.just(new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, initialBuffer, requestConditions, properties, contextFinal)); }).block(); } /** * Opens a seekable byte channel in read-only mode to download the blob. * * @param options {@link BlobSeekableByteChannelReadOptions} * @param context {@link Context} * @return A <code>SeekableByteChannel</code> that represents the channel to use for reading from the blob. * @throws BlobStorageException If a storage service error occurred. */ public BlobSeekableByteChannelReadResult openSeekableByteChannelRead( BlobSeekableByteChannelReadOptions options, Context context) { context = context == null ? Context.NONE : context; options = options == null ? new BlobSeekableByteChannelReadOptions() : options; ConsistentReadControl consistentReadControl = options.getConsistentReadControl() == null ? ConsistentReadControl.ETAG : options.getConsistentReadControl(); int chunkSize = options.getReadSizeInBytes() == null ? 4 * Constants.MB : options.getReadSizeInBytes(); long initialPosition = options.getInitialPosition() == null ? 0 : options.getInitialPosition(); ByteBuffer initialRange = ByteBuffer.allocate(chunkSize); BlobProperties properties; BlobDownloadResponse response; try (ByteBufferBackedOutputStreamUtil dstStream = new ByteBufferBackedOutputStreamUtil(initialRange)) { response = this.downloadStreamWithResponse(dstStream, new BlobRange(initialPosition, (long) initialRange.remaining()), null /*downloadRetryOptions*/, options.getRequestConditions(), false, null, context); properties = ModelHelper.buildBlobPropertiesResponse(response).getValue(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } initialRange.limit(initialRange.position()); initialRange.rewind(); BlobClientBase behaviorClient = this; BlobRequestConditions requestConditions = options.getRequestConditions(); switch (consistentReadControl) { case NONE: break; case ETAG: requestConditions = requestConditions != null ? requestConditions : new BlobRequestConditions(); if (requestConditions.getIfMatch() == null) { requestConditions.setIfMatch(properties.getETag()); } break; case VERSION_ID: if (properties.getVersionId() == null) { throw LOGGER.logExceptionAsError( new UnsupportedOperationException( "Version ID locking unsupported. Versioning is not supported on this account.")); } else { if (getVersionId() == null) { behaviorClient = this.getVersionClient(properties.getVersionId()); } } break; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Concurrency control type " + consistentReadControl + " not supported.")); } StorageSeekableByteChannelBlobReadBehavior behavior = new StorageSeekableByteChannelBlobReadBehavior( behaviorClient, initialRange, initialPosition, properties.getBlobSize(), requestConditions); SeekableByteChannel channel = new StorageSeekableByteChannel(chunkSize, behavior, initialPosition); return new BlobSeekableByteChannelReadResult(channel, properties); } /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.exists --> * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.exists --> * * @return true if the blob exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Boolean exists() { return existsWithResponse(null, Context.NONE).getValue(); } /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return true if the blob exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Boolean> existsWithResponse(Duration timeout, Context context) { try { Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().getPropertiesNoCustomHeadersWithResponse(containerName, blobName, snapshot, versionId, null, null, null, null, null, null, null, null, customerProvidedKey, context)); return new SimpleResponse<>(sendRequest(operation, timeout, BlobStorageException.class), true); } catch (RuntimeException e) { if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); if (e instanceof BlobStorageException && BlobErrorCode.BLOB_USES_CUSTOMER_SPECIFIED_ENCRYPTION.equals(((BlobStorageException) e).getErrorCode())) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), true); } else if (ModelHelper.checkBlobDoesNotExistStatusCode(e)) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); } else { throw LOGGER.logExceptionAsError(e); } } else { throw LOGGER.logExceptionAsError(e); } } } /** * Copies the data at the source URL to a blob. * <p> * This method triggers a long-running, asynchronous operations. The source may be another blob or an Azure File. If * the source is in another account, the source must either be public or authenticated with a SAS token. If the * source is in the same account, the Shared Key authorization on the destination will also be applied to the * source. The source URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.beginCopy * <pre> * final SyncPoller&lt;BlobCopyInfo, Void&gt; poller = client.beginCopy& * PollResponse&lt;BlobCopyInfo&gt; pollResponse = poller.poll& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.beginCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second * is used. * @return A {@link SyncPoller} to poll the progress of blob copy operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public SyncPoller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Duration pollInterval) { return beginCopy(sourceUrl, null, null, null, null, null, pollInterval); } /** * Copies the data at the source URL to a blob. * <p> * This method triggers a long-running, asynchronous operations. The source may be another blob or an Azure File. If * the source is in another account, the source must either be public or authenticated with a SAS token. If the * source is in the same account, the Shared Key authorization on the destination will also be applied to the * source. The source URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.beginCopy * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * RequestConditions modifiedRequestConditions = new RequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * SyncPoller&lt;BlobCopyInfo, Void&gt; poller = client.beginCopy& * RehydratePriority.STANDARD, modifiedRequestConditions, blobRequestConditions, Duration.ofSeconds& * * PollResponse&lt;BlobCopyInfo&gt; response = poller.waitUntil& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.beginCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. If there is leading or trailing whitespace in * any metadata key or value, it must be removed or encoded. * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedRequestConditions {@link RequestConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destRequestConditions {@link BlobRequestConditions} against the destination. * @param pollInterval Duration between each poll for the copy status. If none is specified, a default of one second * is used. * @return A {@link SyncPoller} to poll the progress of blob copy operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public SyncPoller<BlobCopyInfo, Void> beginCopy(String sourceUrl, Map<String, String> metadata, AccessTier tier, RehydratePriority priority, RequestConditions sourceModifiedRequestConditions, BlobRequestConditions destRequestConditions, Duration pollInterval) { return this.beginCopy(new BlobBeginCopyOptions(sourceUrl).setMetadata(metadata).setTier(tier) .setRehydratePriority(priority).setSourceRequestConditions( ModelHelper.populateBlobSourceRequestConditions(sourceModifiedRequestConditions)) .setDestinationRequestConditions(destRequestConditions).setPollInterval(pollInterval)); } /** * Copies the data at the source URL to a blob. * <p> * This method triggers a long-running, asynchronous operations. The source may be another blob or an Azure File. If * the source is in another account, the source must either be public or authenticated with a SAS token. If the * source is in the same account, the Shared Key authorization on the destination will also be applied to the * source. The source URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.beginCopy * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Map&lt;String, String&gt; tags = Collections.singletonMap& * BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * SyncPoller&lt;BlobCopyInfo, Void&gt; poller = client.beginCopy& * .setTags& * .setSourceRequestConditions& * .setDestinationRequestConditions& * * PollResponse&lt;BlobCopyInfo&gt; response = poller.waitUntil& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.beginCopy * * <p>For more information, see the * <a href="https: * * @param options {@link BlobBeginCopyOptions} * @return A {@link SyncPoller} to poll the progress of blob copy operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public SyncPoller<BlobCopyInfo, Void> beginCopy(BlobBeginCopyOptions options) { StorageImplUtils.assertNotNull("options", options); final AtomicReference<String> copyId = new AtomicReference<>(); final Duration interval = options.getPollInterval() != null ? options.getPollInterval() : Duration.ofSeconds(1); final BlobBeginCopySourceRequestConditions sourceModifiedConditions = options.getSourceRequestConditions() == null ? new BlobBeginCopySourceRequestConditions() : options.getSourceRequestConditions(); final BlobRequestConditions destinationRequestConditions = options.getDestinationRequestConditions() == null ? new BlobRequestConditions() : options.getDestinationRequestConditions(); final BlobImmutabilityPolicy immutabilityPolicy = options.getImmutabilityPolicy() == null ? new BlobImmutabilityPolicy() : options.getImmutabilityPolicy(); Function<PollingContext<BlobCopyInfo>, PollResponse<BlobCopyInfo>> syncActivationOperation = (pollingContext) -> { try { new URL(options.getSourceUrl()); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'sourceUrl' is not a valid url.", ex)); } ResponseBase<BlobsStartCopyFromURLHeaders, Void> response = wrapServiceCallWithExceptionMapping(() -> azureBlobStorage.getBlobs().startCopyFromURLWithResponse( containerName, blobName, options.getSourceUrl(), null, options.getMetadata(), options.getTier(), options.getRehydratePriority(), sourceModifiedConditions.getIfModifiedSince(), sourceModifiedConditions.getIfUnmodifiedSince(), sourceModifiedConditions.getIfMatch(), sourceModifiedConditions.getIfNoneMatch(), sourceModifiedConditions.getTagsConditions(), destinationRequestConditions.getIfModifiedSince(), destinationRequestConditions.getIfUnmodifiedSince(), destinationRequestConditions.getIfMatch(), destinationRequestConditions.getIfNoneMatch(), destinationRequestConditions.getTagsConditions(), destinationRequestConditions.getLeaseId(), null, ModelHelper.tagsToString(options.getTags()), options.isSealDestination(), immutabilityPolicy.getExpiryTime(), immutabilityPolicy.getPolicyMode(), options.isLegalHold(), Context.NONE)); BlobsStartCopyFromURLHeaders headers = response.getDeserializedHeaders(); copyId.set(headers.getXMsCopyId()); return new PollResponse<>( LongRunningOperationStatus.IN_PROGRESS, new BlobCopyInfo(options.getSourceUrl(), headers.getXMsCopyId(), headers.getXMsCopyStatus(), headers.getETag(), headers.getLastModified(), ModelHelper.getErrorCode(response.getHeaders()), headers.getXMsVersionId()) ); }; Function<PollingContext<BlobCopyInfo>, PollResponse<BlobCopyInfo>> pollOperation = (pollingContext) -> onPoll(pollingContext.getLatestResponse(), destinationRequestConditions); BiFunction<PollingContext<BlobCopyInfo>, PollResponse<BlobCopyInfo>, BlobCopyInfo> cancelOperation = (pollingContext, firstResponse) -> { if (firstResponse == null || firstResponse.getValue() == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Cannot cancel a poll response that never started.")); } final String copyIdentifier = firstResponse.getValue().getCopyId(); if (!CoreUtils.isNullOrEmpty(copyIdentifier)) { LOGGER.info("Cancelling copy operation for copy id: {}", copyIdentifier); abortCopyFromUrl(copyIdentifier); return firstResponse.getValue(); } return null; }; Function<PollingContext<BlobCopyInfo>, Void> fetchResultOperation = (pollingContext) -> null; return SyncPoller.createPoller(interval, syncActivationOperation, pollOperation, cancelOperation, fetchResultOperation); } private PollResponse<BlobCopyInfo> onPoll(PollResponse<BlobCopyInfo> pollResponse, BlobRequestConditions requestConditions) { if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) { return pollResponse; } final BlobCopyInfo lastInfo = pollResponse.getValue(); if (lastInfo == null) { LOGGER.warning("BlobCopyInfo does not exist. Activation operation failed."); return new PollResponse<>(LongRunningOperationStatus.fromString("COPY_START_FAILED", true), null); } try { Response<BlobProperties> response = getPropertiesWithResponse(requestConditions, null, null); BlobProperties value = response.getValue(); final CopyStatusType status = value.getCopyStatus(); final BlobCopyInfo result = new BlobCopyInfo(value.getCopySource(), value.getCopyId(), status, value.getETag(), value.getCopyCompletionTime(), value.getCopyStatusDescription(), value.getVersionId()); LongRunningOperationStatus operationStatus = ModelHelper.mapStatusToLongRunningOperationStatus(status); return new PollResponse<>(operationStatus, result); } catch (RuntimeException e) { return new PollResponse<>(LongRunningOperationStatus.fromString("POLLING_FAILED", true), lastInfo); } } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl * <pre> * client.abortCopyFromUrl& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. */ @ServiceMethod(returns = ReturnType.SINGLE) public void abortCopyFromUrl(String copyId) { abortCopyFromUrlWithResponse(copyId, null, null, Context.NONE); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse * <pre> * System.out.printf& * client.abortCopyFromUrlWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. * @param leaseId The lease ID the active lease on the blob must match. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> abortCopyFromUrlWithResponse(String copyId, String leaseId, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().abortCopyFromURLNoCustomHeadersWithResponse(containerName, blobName, copyId, null, leaseId, null, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * <p> * The source must be a block blob no larger than 256MB. The source must also be either public or have a sas token * attached. The URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return The copy ID for the long running operation. * @throws IllegalArgumentException If {@code copySource} is a malformed {@link URL}. */ @ServiceMethod(returns = ReturnType.SINGLE) public String copyFromUrl(String copySource) { return copyFromUrlWithResponse(copySource, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * <p> * The source must be a block blob no larger than 256MB. The source must also be either public or have a sas token * attached. The URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * RequestConditions modifiedRequestConditions = new RequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * * System.out.printf& * client.copyFromUrlWithResponse& * blobRequestConditions, timeout, * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. If there is leading or trailing whitespace in * any metadata key or value, it must be removed or encoded. * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedRequestConditions {@link RequestConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destRequestConditions {@link BlobRequestConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. * @throws IllegalArgumentException If {@code copySource} is a malformed {@link URL}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<String> copyFromUrlWithResponse(String copySource, Map<String, String> metadata, AccessTier tier, RequestConditions sourceModifiedRequestConditions, BlobRequestConditions destRequestConditions, Duration timeout, Context context) { return this.copyFromUrlWithResponse(new BlobCopyFromUrlOptions(copySource).setMetadata(metadata) .setTier(tier).setSourceRequestConditions(sourceModifiedRequestConditions) .setDestinationRequestConditions(destRequestConditions), timeout, context); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * <p> * The source must be a block blob no larger than 256MB. The source must also be either public or have a sas token * attached. The URL must be URL encoded. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * <pre> * Map&lt;String, String&gt; metadata = Collections.singletonMap& * Map&lt;String, String&gt; tags = Collections.singletonMap& * RequestConditions modifiedRequestConditions = new RequestConditions& * .setIfUnmodifiedSince& * BlobRequestConditions blobRequestConditions = new BlobRequestConditions& * * System.out.printf& * client.copyFromUrlWithResponse& * .setTier& * .setDestinationRequestConditions& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobCopyFromUrlOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. * @throws IllegalArgumentException If {@code copySource} is a malformed {@link URL}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<String> copyFromUrlWithResponse(BlobCopyFromUrlOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); RequestConditions sourceModifiedRequestConditions = options.getSourceRequestConditions() == null ? new RequestConditions() : options.getSourceRequestConditions(); BlobRequestConditions destRequestConditions = options.getDestinationRequestConditions() == null ? new BlobRequestConditions() : options.getDestinationRequestConditions(); BlobImmutabilityPolicy immutabilityPolicy = options.getImmutabilityPolicy() == null ? new BlobImmutabilityPolicy() : options.getImmutabilityPolicy(); try { new URL(options.getCopySource()); } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'copySource' is not a valid url.", ex)); } String sourceAuth = options.getSourceAuthorization() == null ? null : options.getSourceAuthorization().toString(); Callable<ResponseBase<BlobsCopyFromURLHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().copyFromURLWithResponse(containerName, blobName, options.getCopySource(), null, options.getMetadata(), options.getTier(), sourceModifiedRequestConditions.getIfModifiedSince(), sourceModifiedRequestConditions.getIfUnmodifiedSince(), sourceModifiedRequestConditions.getIfMatch(), sourceModifiedRequestConditions.getIfNoneMatch(), destRequestConditions.getIfModifiedSince(), destRequestConditions.getIfUnmodifiedSince(), destRequestConditions.getIfMatch(), destRequestConditions.getIfNoneMatch(), destRequestConditions.getTagsConditions(), destRequestConditions.getLeaseId(), null, null, ModelHelper.tagsToString(options.getTags()), immutabilityPolicy.getExpiryTime(), immutabilityPolicy.getPolicyMode(), options.hasLegalHold(), sourceAuth, options.getCopySourceTagsMode(), this.encryptionScope, context)); ResponseBase<BlobsCopyFromURLHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, response.getDeserializedHeaders().getXMsCopyId()); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.download * <pre> * client.download& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.download * * <p>For more information, see the * <a href="https: * * <p>This method will be deprecated in the future. Use {@link * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null * @deprecated use {@link */ @ServiceMethod(returns = ReturnType.SINGLE) @Deprecated public void download(OutputStream stream) { downloadStream(stream); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadStream * <pre> * client.downloadStream& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadStream * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null */ @ServiceMethod(returns = ReturnType.SINGLE) public void downloadStream(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * Downloads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.BlobClient.downloadContent --> * <pre> * BinaryData data = client.downloadContent& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.BlobClient.downloadContent --> * * <p>For more information, see the * <a href="https: * * <p>This method supports downloads up to 2GB of data. Content will be buffered in memory. If the blob is larger, * use {@link * * @return The content of the blob. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public BinaryData downloadContent() { return blockWithOptionalTimeout(client.downloadContent(), null); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * <pre> * BlobRange range = new BlobRange& * DownloadRetryOptions options = new DownloadRetryOptions& * * System.out.printf& * client.downloadWithResponse& * timeout, new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * <p>This method will be deprecated in the future. * Use {@link * BlobRequestConditions, boolean, Duration, Context)} instead. * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null * @deprecated use {@link */ @ServiceMethod(returns = ReturnType.SINGLE) @Deprecated public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { return downloadStreamWithResponse(stream, range, options, requestConditions, getRangeContentMd5, timeout, context); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse * <pre> * BlobRange range = new BlobRange& * DownloadRetryOptions options = new DownloadRetryOptions& * * System.out.printf& * client.downloadStreamWithResponse& * timeout, new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobDownloadResponse downloadStreamWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadStreamWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> FluxUtil.writeToOutputStream(response.getValue(), stream) .thenReturn(new BlobDownloadResponse(response))); return blockWithOptionalTimeout(download, timeout); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * <pre> * DownloadRetryOptions options = new DownloadRetryOptions& * * BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse& * timeout, new Context& * BinaryData content = contentResponse.getValue& * System.out.printf& * contentResponse.getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * * <p>For more information, see the * <a href="https: * * <p>This method supports downloads up to 2GB of data. Content will be buffered in memory. If the blob is larger, * use {@link * DownloadRetryOptions, BlobRequestConditions, boolean, Duration, Context)} to download larger blobs.</p> * * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobDownloadContentResponse downloadContentWithResponse( DownloadRetryOptions options, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<BlobDownloadContentResponse> download = client .downloadStreamWithResponse(null, options, requestConditions, false, context) .flatMap(r -> BinaryData.fromFlux(r.getValue()) .map(data -> new BlobDownloadContentAsyncResponse( r.getRequest(), r.getStatusCode(), r.getHeaders(), data, r.getDeserializedHeaders()) )) .map(BlobDownloadContentResponse::new); return blockWithOptionalTimeout(download, timeout); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * <pre> * DownloadRetryOptions options = new DownloadRetryOptions& * BlobRange range = new BlobRange& * * BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse& * range, false, timeout, new Context& * BinaryData content = contentResponse.getValue& * System.out.printf& * contentResponse.getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse * * <p>For more information, see the * <a href="https: * * <p>This method supports downloads up to 2GB of data. Content will be buffered in memory. If the blob is larger, * use {@link * DownloadRetryOptions, BlobRequestConditions, boolean, Duration, Context)} to download larger blobs.</p> * * @param options {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param range {@link BlobRange} * @param getRangeContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobDownloadContentResponse downloadContentWithResponse(DownloadRetryOptions options, BlobRequestConditions requestConditions, BlobRange range, boolean getRangeContentMd5, Duration timeout, Context context) { Mono<BlobDownloadContentResponse> download = client .downloadStreamWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(r -> BinaryData.fromFlux(r.getValue()) .map(data -> new BlobDownloadContentAsyncResponse( r.getRequest(), r.getStatusCode(), r.getHeaders(), data, r.getDeserializedHeaders()) )) .map(BlobDownloadContentResponse::new); return blockWithOptionalTimeout(download, timeout); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * <pre> * client.downloadToFile& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobProperties downloadToFile(String filePath) { return downloadToFile(filePath, false); } /** * Downloads the entire blob into a file specified by the path. * * <p>If overwrite is set to false, the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * <pre> * boolean overwrite = false; & * client.downloadToFile& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param overwrite Whether to overwrite the file, should the file exist. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobProperties downloadToFile(String filePath, boolean overwrite) { Set<OpenOption> openOptions = null; if (overwrite) { openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.CREATE); openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); openOptions.add(StandardOpenOption.READ); openOptions.add(StandardOpenOption.WRITE); } return downloadToFileWithResponse(filePath, null, null, null, null, false, openOptions, null, Context.NONE) .getValue(); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * <pre> * BlobRange range = new BlobRange& * DownloadRetryOptions options = new DownloadRetryOptions& * * client.downloadToFileWithResponse& * options, null, false, timeout, new Context& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link BlobRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param downloadRetryOptions {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Duration timeout, Context context) { return downloadToFileWithResponse(filePath, range, parallelTransferOptions, downloadRetryOptions, requestConditions, rangeGetContentMd5, null, timeout, context); } /** * Downloads the entire blob into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * <pre> * BlobRange blobRange = new BlobRange& * DownloadRetryOptions downloadRetryOptions = new DownloadRetryOptions& * Set&lt;OpenOption&gt; openOptions = new HashSet&lt;&gt;& * StandardOpenOption.WRITE, StandardOpenOption.READ& * * client.downloadToFileWithResponse& * downloadRetryOptions, null, false, openOptions, timeout, new Context& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link BlobRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param downloadRetryOptions {@link DownloadRetryOptions} * @param requestConditions {@link BlobRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified blob range should be returned. * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Set<OpenOption> openOptions, Duration timeout, Context context) { final com.azure.storage.common.ParallelTransferOptions finalParallelTransferOptions = ModelHelper.wrapBlobOptions(ModelHelper.populateAndApplyDefaults(parallelTransferOptions)); return downloadToFileWithResponse(new BlobDownloadToFileOptions(filePath).setRange(range) .setParallelTransferOptions(finalParallelTransferOptions) .setDownloadRetryOptions(downloadRetryOptions).setRequestConditions(requestConditions) .setRetrieveContentRangeMd5(rangeGetContentMd5).setOpenOptions(openOptions), timeout, context); } /** * Downloads the entire blob into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * <pre> * client.downloadToFileWithResponse& * .setRange& * .setDownloadRetryOptions& * .setOpenOptions& * StandardOpenOption.READ& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobDownloadToFileOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> downloadToFileWithResponse(BlobDownloadToFileOptions options, Duration timeout, Context context) { Mono<Response<BlobProperties>> download = client.downloadToFileWithResponse(options, context); return blockWithOptionalTimeout(download, timeout); } /** * Deletes the specified blob or snapshot. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.delete --> * <pre> * client.delete& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.delete --> * * <p>For more information, see the * <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * <pre> * System.out.printf& * client.deleteWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> azureBlobStorage.getBlobs().deleteNoCustomHeadersWithResponse(containerName, blobName, snapshot, versionId, null, finalRequestConditions.getLeaseId(), deleteBlobSnapshotOptions, finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, null, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Deletes the specified blob or snapshot if it exists. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists --> * <pre> * boolean result = client.deleteIfExists& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists --> * * <p>For more information, see the * <a href="https: * @return {@code true} if delete succeeds, or {@code false} if blob does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public boolean deleteIfExists() { return deleteIfExistsWithResponse(null, null, null, Context.NONE).getValue(); } /** * Deletes the specified blob or snapshot if it exists. To delete a blob with its snapshots use * {@link * {@code DeleteSnapshotsOptionType} to INCLUDE. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse * <pre> * Response&lt;Boolean&gt; response = client.deleteIfExistsWithResponse& * new Context& * if & * System.out.println& * & * System.out.printf& * & * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. If {@link Response}'s status code is 202, the base * blob was successfully deleted. If status code is 404, the base blob does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Boolean> deleteIfExistsWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { try { Response<Void> response = this.deleteWithResponse(deleteBlobSnapshotOptions, requestConditions, timeout, context); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), true); } catch (RuntimeException e) { if (ModelHelper.checkBlobDoesNotExistStatusCode(e) && e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); } else { throw LOGGER.logExceptionAsError(e); } } } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getProperties --> * <pre> * BlobProperties properties = client.getProperties& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getProperties --> * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * <pre> * BlobRequestConditions requestConditions = new BlobRequestConditions& * * BlobProperties properties = client.getPropertiesWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobProperties> getPropertiesWithResponse(BlobRequestConditions requestConditions, Duration timeout, Context context) { BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsGetPropertiesHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().getPropertiesWithResponse(containerName, blobName, snapshot, versionId, null, finalRequestConditions.getLeaseId(), finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, customerProvidedKey, finalContext)); ResponseBase<BlobsGetPropertiesHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, BlobPropertiesConstructorProxy .create(new BlobPropertiesInternalGetProperties(response.getDeserializedHeaders()))); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * <pre> * client.setHttpHeaders& * .setContentLanguage& * .setContentType& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} */ @ServiceMethod(returns = ReturnType.SINGLE) public void setHttpHeaders(BlobHttpHeaders headers) { setHttpHeadersWithResponse(headers, null, null, Context.NONE); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse * <pre> * BlobRequestConditions requestConditions = new BlobRequestConditions& * * System.out.printf& * client.setHttpHeadersWithResponse& * .setContentLanguage& * .setContentType& * .getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobRequestConditions requestConditions, Duration timeout, Context context) { BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().setHttpHeadersNoCustomHeadersWithResponse(containerName, blobName, null, finalRequestConditions.getLeaseId(), finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, headers, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setMetadata * <pre> * client.setMetadata& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setMetadata(Map<String, String> metadata) { setMetadataWithResponse(metadata, null, null, Context.NONE); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * <pre> * BlobRequestConditions requestConditions = new BlobRequestConditions& * * System.out.printf& * client.setMetadataWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setMetadataWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().setMetadataNoCustomHeadersWithResponse(containerName, blobName, null, metadata, finalRequestConditions.getLeaseId(), finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), null, customerProvidedKey, encryptionScope, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getTags --> * <pre> * Map&lt;String, String&gt; tags = client.getTags& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getTags --> * * <p>For more information, see the * <a href="https: * * @return The blob's tags. */ @ServiceMethod(returns = ReturnType.SINGLE) public Map<String, String> getTags() { return this.getTagsWithResponse(new BlobGetTagsOptions(), null, Context.NONE).getValue(); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse * <pre> * Map&lt;String, String&gt; tags = client.getTagsWithResponse& * new Context& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobGetTagsOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob's tags. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Map<String, String>> getTagsWithResponse(BlobGetTagsOptions options, Duration timeout, Context context) { BlobGetTagsOptions finalTagOptions = (options == null) ? new BlobGetTagsOptions() : options; BlobRequestConditions requestConditions = (finalTagOptions.getRequestConditions() == null) ? new BlobRequestConditions() : finalTagOptions.getRequestConditions(); Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsGetTagsHeaders, BlobTags>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().getTagsWithResponse(containerName, blobName, null, null, snapshot, versionId, requestConditions.getTagsConditions(), requestConditions.getLeaseId(), finalContext)); ResponseBase<BlobsGetTagsHeaders, BlobTags> response = sendRequest(operation, timeout, BlobStorageException.class); Map<String, String> tags = new HashMap<>(); for (BlobTag tag : response.getValue().getBlobTagSet()) { tags.put(tag.getKey(), tag.getValue()); } return new SimpleResponse<>(response, tags); } /** * Sets user defined tags. The specified tags in this method will replace existing tags. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setTags * <pre> * client.setTags& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setTags * * <p>For more information, see the * <a href="https: * * @param tags Tags to associate with the blob. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setTags(Map<String, String> tags) { this.setTagsWithResponse(new BlobSetTagsOptions(tags), null, Context.NONE); } /** * Sets user defined tags. The specified tags in this method will replace existing tags. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse * <pre> * System.out.printf& * client.setTagsWithResponse& * new Context& * .getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobSetTagsOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setTagsWithResponse(BlobSetTagsOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions requestConditions = (options.getRequestConditions() == null) ? new BlobRequestConditions() : options.getRequestConditions(); List<BlobTag> tagList = null; if (options.getTags() != null) { tagList = new ArrayList<>(); for (Map.Entry<String, String> entry : options.getTags().entrySet()) { tagList.add(new BlobTag().setKey(entry.getKey()).setValue(entry.getValue())); } } BlobTags t = new BlobTags().setBlobTagSet(tagList); Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().setTagsNoCustomHeadersWithResponse(containerName, blobName, null, versionId, null, null, null, requestConditions.getTagsConditions(), requestConditions.getLeaseId(), t, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.createSnapshot --> * <pre> * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.createSnapshot --> * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobClientBase} which is used to interact with the created snapshot, use * {@link BlobClientBase */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobClientBase createSnapshot() { return createSnapshotWithResponse(null, null, null, Context.NONE).getValue(); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * <pre> * Map&lt;String, String&gt; snapshotMetadata = Collections.singletonMap& * BlobRequestConditions requestConditions = new BlobRequestConditions& * * System.out.printf& * client.createSnapshotWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing a {@link BlobClientBase} which is used to interact with the created snapshot, use * {@link BlobClientBase */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobClientBase> createSnapshotWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; Callable<ResponseBase<BlobsCreateSnapshotHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().createSnapshotWithResponse(containerName, blobName, null, metadata, finalRequestConditions.getIfModifiedSince(), finalRequestConditions.getIfUnmodifiedSince(), finalRequestConditions.getIfMatch(), finalRequestConditions.getIfNoneMatch(), finalRequestConditions.getTagsConditions(), finalRequestConditions.getLeaseId(), null, customerProvidedKey, encryptionScope, finalContext)); ResponseBase<BlobsCreateSnapshotHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, this.getSnapshotClient(response.getDeserializedHeaders().getXMsSnapshot())); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * <pre> * client.setAccessTier& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ @ServiceMethod(returns = ReturnType.SINGLE) public void setAccessTier(AccessTier tier) { setAccessTierWithResponse(tier, null, null, null, Context.NONE); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * <pre> * System.out.printf& * client.setAccessTierWithResponse& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseId The lease ID the active lease on the blob must match. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority, String leaseId, Duration timeout, Context context) { return setAccessTierWithResponse(new BlobSetAccessTierOptions(tier).setPriority(priority).setLeaseId(leaseId), timeout, context); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * <pre> * System.out.printf& * client.setAccessTierWithResponse& * .setPriority& * .setLeaseId& * .setTagsConditions& * timeout, new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link BlobSetAccessTierOptions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> setAccessTierWithResponse(BlobSetAccessTierOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().setTierNoCustomHeadersWithResponse(containerName, blobName, options.getTier(), snapshot, versionId, null, options.getPriority(), null, options.getLeaseId(), options.getTagsConditions(), finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.undelete --> * <pre> * client.undelete& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.undelete --> * * <p>For more information, see the * <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public void undelete() { undeleteWithResponse(null, Context.NONE); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * <pre> * System.out.printf& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().undeleteNoCustomHeadersWithResponse(containerName, blobName, null, null, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo --> * <pre> * StorageAccountInfo accountInfo = client.getAccountInfo& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo --> * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ @ServiceMethod(returns = ReturnType.SINGLE) public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * <pre> * StorageAccountInfo accountInfo = client.getAccountInfoWithResponse& * System.out.printf& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The sku name and account kind. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsGetAccountInfoHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().getAccountInfoWithResponse(containerName, blobName, finalContext)); ResponseBase<BlobsGetAccountInfoHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); BlobsGetAccountInfoHeaders hd = response.getDeserializedHeaders(); return new SimpleResponse<>(response, new StorageAccountInfo(hd.getXMsSkuName(), hd.getXMsAccountKind())); } /** * Generates a user delegation SAS for the blob using the specified {@link BlobServiceSasSignatureValues}. * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a user delegation SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * BlobSasPermission myPermission = new BlobSasPermission& * * BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link BlobServiceClient * how to get a user delegation key. * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey, getAccountName(), Context.NONE); } /** * Generates a user delegation SAS for the blob using the specified {@link BlobServiceSasSignatureValues}. * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a user delegation SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * BlobSasPermission myPermission = new BlobSasPermission& * * BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link BlobServiceClient * how to get a user delegation key. * @param accountName The account name. * @param context Additional context that is passed through the code when generating a SAS. * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey, String accountName, Context context) { return generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey, accountName, null, context); } /** * Generates a user delegation SAS for the blob using the specified {@link BlobServiceSasSignatureValues}. * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a user delegation SAS.</p> * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link BlobServiceClient * how to get a user delegation key. * @param accountName The account name. * @param stringToSignHandler For debugging purposes only. Returns the string to sign that was used to generate the * signature. * @param context Additional context that is passed through the code when generating a SAS. * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey, String accountName, Consumer<String> stringToSignHandler, Context context) { return new BlobSasImplUtil(blobServiceSasSignatureValues, getContainerName(), getBlobName(), getSnapshotId(), getVersionId(), getEncryptionScope()) .generateUserDelegationSas(userDelegationKey, accountName, stringToSignHandler, context); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * BlobSasPermission permission = new BlobSasPermission& * * BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues& * .setStartTime& * * client.generateSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues) { return generateSas(blobServiceSasSignatureValues, Context.NONE); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * BlobSasPermission permission = new BlobSasPermission& * * BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues& * .setStartTime& * * & * client.generateSas& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, Context context) { return generateSas(blobServiceSasSignatureValues, null, context); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link BlobServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param stringToSignHandler For debugging purposes only. Returns the string to sign that was used to generate the * signature. * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, Consumer<String> stringToSignHandler, Context context) { return new BlobSasImplUtil(blobServiceSasSignatureValues, getContainerName(), getBlobName(), getSnapshotId(), getVersionId(), getEncryptionScope()) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), stringToSignHandler, context); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * <pre> * String expression = &quot;SELECT * from BlobStorage&quot;; * InputStream inputStream = client.openQueryInputStream& * & * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * * @param expression The query expression. * @return An <code>InputStream</code> object that represents the stream to use for reading the query response. */ @ServiceMethod(returns = ReturnType.SINGLE) public InputStream openQueryInputStream(String expression) { return openQueryInputStreamWithResponse(new BlobQueryOptions(expression)).getValue(); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * <pre> * String expression = &quot;SELECT * from BlobStorage&quot;; * BlobQuerySerialization input = new BlobQueryDelimitedSerialization& * .setColumnSeparator& * .setEscapeChar& * .setRecordSeparator& * .setHeadersPresent& * .setFieldQuote& * BlobQuerySerialization output = new BlobQueryJsonSerialization& * .setRecordSeparator& * BlobRequestConditions requestConditions = new BlobRequestConditions& * .setLeaseId& * Consumer&lt;BlobQueryError&gt; errorConsumer = System.out::println; * Consumer&lt;BlobQueryProgress&gt; progressConsumer = progress -&gt; System.out.println& * + progress.getBytesScanned& * BlobQueryOptions queryOptions = new BlobQueryOptions& * .setInputSerialization& * .setOutputSerialization& * .setRequestConditions& * .setErrorConsumer& * .setProgressConsumer& * * InputStream inputStream = client.openQueryInputStreamWithResponse& * & * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream * * @param queryOptions {@link BlobQueryOptions The query options}. * @return A response containing status code and HTTP headers including an <code>InputStream</code> object * that represents the stream to use for reading the query response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<InputStream> openQueryInputStreamWithResponse(BlobQueryOptions queryOptions) { StorageImplUtils.assertNotNull("options", queryOptions); BlobRequestConditions requestConditions = queryOptions.getRequestConditions() == null ? new BlobRequestConditions() : queryOptions.getRequestConditions(); QuerySerialization in = BlobQueryReader.transformInputSerialization(queryOptions.getInputSerialization(), LOGGER); QuerySerialization out = BlobQueryReader.transformOutputSerialization(queryOptions.getOutputSerialization(), LOGGER); QueryRequest qr = new QueryRequest() .setExpression(queryOptions.getExpression()) .setInputSerialization(in) .setOutputSerialization(out); ResponseBase<BlobsQueryHeaders, InputStream> response = wrapServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().queryWithResponse(containerName, blobName, getSnapshotId(), null, requestConditions.getLeaseId(), requestConditions.getIfModifiedSince(), requestConditions.getIfUnmodifiedSince(), requestConditions.getIfMatch(), requestConditions.getIfNoneMatch(), requestConditions.getTagsConditions(), null, qr, getCustomerProvidedKey(), Context.NONE)); InputStream avroInputStream = response.getValue(); BlobQueryReader reader = new BlobQueryReader(null, queryOptions.getProgressConsumer(), queryOptions.getErrorConsumer()); try { InputStream resultStream = reader.readInputStream(avroInputStream); return new SimpleResponse<>(response, resultStream); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.query * <pre> * ByteArrayOutputStream queryData = new ByteArrayOutputStream& * String expression = &quot;SELECT * from BlobStorage&quot;; * client.query& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.query * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param expression The query expression. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public void query(OutputStream stream, String expression) { queryWithResponse(new BlobQueryOptions(expression, stream), null, Context.NONE); } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse * <pre> * ByteArrayOutputStream queryData = new ByteArrayOutputStream& * String expression = &quot;SELECT * from BlobStorage&quot;; * BlobQueryJsonSerialization input = new BlobQueryJsonSerialization& * .setRecordSeparator& * BlobQueryDelimitedSerialization output = new BlobQueryDelimitedSerialization& * .setEscapeChar& * .setColumnSeparator& * .setRecordSeparator& * .setFieldQuote& * .setHeadersPresent& * BlobRequestConditions requestConditions = new BlobRequestConditions& * Consumer&lt;BlobQueryError&gt; errorConsumer = System.out::println; * Consumer&lt;BlobQueryProgress&gt; progressConsumer = progress -&gt; System.out.println& * + progress.getBytesScanned& * BlobQueryOptions queryOptions = new BlobQueryOptions& * .setInputSerialization& * .setOutputSerialization& * .setRequestConditions& * .setErrorConsumer& * .setProgressConsumer& * System.out.printf& * client.queryWithResponse& * .getStatusCode& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse * * @param queryOptions {@link BlobQueryOptions The query options}. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. * @throws NullPointerException if {@code stream} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Sets the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy * <pre> * BlobImmutabilityPolicy policy = new BlobImmutabilityPolicy& * .setPolicyMode& * .setExpiryTime& * BlobImmutabilityPolicy setPolicy = client.setImmutabilityPolicy& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy * * @param immutabilityPolicy {@link BlobImmutabilityPolicy The immutability policy}. * @return The immutability policy. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobImmutabilityPolicy setImmutabilityPolicy(BlobImmutabilityPolicy immutabilityPolicy) { return setImmutabilityPolicyWithResponse(immutabilityPolicy, null, null, Context.NONE).getValue(); } /** * Sets the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse * <pre> * BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy& * .setPolicyMode& * .setExpiryTime& * BlobRequestConditions requestConditions = new BlobRequestConditions& * .setIfUnmodifiedSince& * Response&lt;BlobImmutabilityPolicy&gt; response = client.setImmutabilityPolicyWithResponse& * requestConditions, timeout, new Context& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse * * @param immutabilityPolicy {@link BlobImmutabilityPolicy The immutability policy}. * @param requestConditions {@link BlobRequestConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the immutability policy. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobImmutabilityPolicy> setImmutabilityPolicyWithResponse(BlobImmutabilityPolicy immutabilityPolicy, BlobRequestConditions requestConditions, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; BlobImmutabilityPolicy finalImmutabilityPolicy = immutabilityPolicy == null ? new BlobImmutabilityPolicy() : immutabilityPolicy; if (BlobImmutabilityPolicyMode.MUTABLE.equals(finalImmutabilityPolicy.getPolicyMode())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("immutabilityPolicy.policyMode must be %s or %s", BlobImmutabilityPolicyMode.LOCKED.toString(), BlobImmutabilityPolicyMode.UNLOCKED.toString()))); } BlobRequestConditions finalRequestConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; ModelHelper.validateConditionsNotPresent(finalRequestConditions, EnumSet.of(BlobRequestConditionProperty.LEASE_ID, BlobRequestConditionProperty.TAGS_CONDITIONS, BlobRequestConditionProperty.IF_MATCH, BlobRequestConditionProperty.IF_NONE_MATCH, BlobRequestConditionProperty.IF_MODIFIED_SINCE), "setImmutabilityPolicy(WithResponse)", "requestConditions"); Callable<ResponseBase<BlobsSetImmutabilityPolicyHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().setImmutabilityPolicyWithResponse(containerName, blobName, null, null, finalRequestConditions.getIfUnmodifiedSince(), finalImmutabilityPolicy.getExpiryTime(), finalImmutabilityPolicy.getPolicyMode(), finalContext)); ResponseBase<BlobsSetImmutabilityPolicyHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); BlobsSetImmutabilityPolicyHeaders headers = response.getDeserializedHeaders(); BlobImmutabilityPolicy responsePolicy = new BlobImmutabilityPolicy() .setPolicyMode(headers.getXMsImmutabilityPolicyMode()) .setExpiryTime(headers.getXMsImmutabilityPolicyUntilDate()); return new SimpleResponse<>(response, responsePolicy); } /** * Delete the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy --> * <pre> * client.deleteImmutabilityPolicy& * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy --> * */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteImmutabilityPolicy() { deleteImmutabilityPolicyWithResponse(null, Context.NONE).getValue(); } /** * Delete the immutability policy on a blob, blob snapshot or blob version. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse * <pre> * System.out.println& * + client.deleteImmutabilityPolicyWithResponse& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the immutability policy. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteImmutabilityPolicyWithResponse(Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<Response<Void>> operation = wrapTimeoutServiceCallWithExceptionMapping(() -> this.azureBlobStorage.getBlobs().deleteImmutabilityPolicyNoCustomHeadersWithResponse(containerName, blobName, null, null, finalContext)); return sendRequest(operation, timeout, BlobStorageException.class); } /** * Sets a legal hold on the blob. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setLegalHold * <pre> * System.out.println& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setLegalHold * * @param legalHold Whether you want a legal hold on the blob. * @return The legal hold result. */ @ServiceMethod(returns = ReturnType.SINGLE) public BlobLegalHoldResult setLegalHold(boolean legalHold) { return setLegalHoldWithResponse(legalHold, null, Context.NONE).getValue(); } /** * Sets a legal hold on the blob. * <p> NOTE: Blob Versioning must be enabled on your storage account and the blob must be in a container with * immutable storage with versioning enabled to call this API.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse * <pre> * System.out.println& * new Context& * </pre> * <!-- end com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse * * @param legalHold Whether you want a legal hold on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing the legal hold result. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<BlobLegalHoldResult> setLegalHoldWithResponse(boolean legalHold, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; Callable<ResponseBase<BlobsSetLegalHoldHeaders, Void>> operation = wrapTimeoutServiceCallWithExceptionMapping( () -> this.azureBlobStorage.getBlobs().setLegalHoldWithResponse(containerName, blobName, legalHold, null, null, finalContext)); ResponseBase<BlobsSetLegalHoldHeaders, Void> response = sendRequest(operation, timeout, BlobStorageException.class); return new SimpleResponse<>(response, new InternalBlobLegalHoldResult(response.getDeserializedHeaders().isXMsLegalHold())); } }
Will follow up with this in the PR when converting internal-avro.
public InputStream readInputStream(InputStream inputStream) throws IOException { Flux<ByteBuffer> avroFlux = toFluxByteBuffer(inputStream); Flux<ByteBuffer> processedData = new AvroReaderFactory().getAvroReader(avroFlux).read() .map(AvroObject::getObject) .concatMap(this::parseRecord); return new FluxInputStream(processedData); }
Flux<ByteBuffer> processedData = new AvroReaderFactory().getAvroReader(avroFlux).read()
public InputStream readInputStream(InputStream inputStream) throws IOException { AvroReaderSyncFactory avroReaderSyncFactory = new AvroReaderSyncFactory(); ByteBuffer fullBuffer = convertInputStreamToByteBuffer(inputStream); Iterable<AvroObject> avroObjects = avroReaderSyncFactory.getAvroReader(fullBuffer).read(); byte[] processedData = serializeAvroObjectsToBytes(avroObjects); return new ByteArrayInputStream(processedData); }
class BlobQueryReader { private final Flux<ByteBuffer> avro; private final Consumer<BlobQueryProgress> progressConsumer; private final Consumer<BlobQueryError> errorConsumer; /** * Creates a new BlobQueryReader. * * @param avro The reactive avro stream. * @param progressConsumer The progress consumer. * @param errorConsumer The error consumer. */ public BlobQueryReader(Flux<ByteBuffer> avro, Consumer<BlobQueryProgress> progressConsumer, Consumer<BlobQueryError> errorConsumer) { this.avro = avro; this.progressConsumer = progressConsumer; this.errorConsumer = errorConsumer; } /** * Avro parses a query reactive stream. * * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @return The parsed query reactive stream. */ public Flux<ByteBuffer> read() { return new AvroReaderFactory().getAvroReader(avro).read() .map(AvroObject::getObject) .concatMap(this::parseRecord); } /** * Avro parses a query reactive stream. * * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @return The parsed query reactive stream. */ private Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { return FluxUtil.toFluxByteBuffer(inputStream); } /** * Parses a query record. * * @param quickQueryRecord The query record. * @return The optional data in the record. */ private Mono<ByteBuffer> parseRecord(Object quickQueryRecord) { if (!(quickQueryRecord instanceof Map)) { return Mono.error(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> record = (Map<?, ?>) quickQueryRecord; Object recordSchema = record.get(AvroConstants.RECORD); switch (recordSchema.toString()) { case "resultData": return parseResultData(record); case "end": return parseEnd(record); case "progress": return parseProgress(record); case "error": return parseError(record); default: return Mono.error(new IllegalStateException(String.format("Unknown record type %s " + "while parsing query response. ", recordSchema.toString()))); } } /** * Parses a query result data record. * @param dataRecord The query result data record. * @return The data in the record. */ private Mono<ByteBuffer> parseResultData(Map<?, ?> dataRecord) { Object data = dataRecord.get("data"); if (checkParametersNotNull(data)) { AvroSchema.checkType("data", data, List.class); return Mono.just(ByteBuffer.wrap(AvroSchema.getBytes((List<?>) data))); } else { return Mono.error(new IllegalArgumentException("Failed to parse result data record from " + "query response stream.")); } } /** * Parses a query end record. * @param endRecord The query end record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseEnd(Map<?, ?> endRecord) { if (progressConsumer != null) { Object totalBytes = endRecord.get("totalBytes"); if (checkParametersNotNull(totalBytes)) { AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) totalBytes, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse end record from query " + "response stream.")); } } return Mono.empty(); } /** * Parses a query progress record. * @param progressRecord The query progress record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseProgress(Map<?, ?> progressRecord) { if (progressConsumer != null) { Object bytesScanned = progressRecord.get("bytesScanned"); Object totalBytes = progressRecord.get("totalBytes"); if (checkParametersNotNull(bytesScanned, totalBytes)) { AvroSchema.checkType("bytesScanned", bytesScanned, Long.class); AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) bytesScanned, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse progress record from " + "query response stream.")); } } return Mono.empty(); } /** * Parses a query error record. * @param errorRecord The query error record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseError(Map<?, ?> errorRecord) { Object fatal = errorRecord.get("fatal"); Object name = errorRecord.get("name"); Object description = errorRecord.get("description"); Object position = errorRecord.get("position"); if (checkParametersNotNull(fatal, name, description, position)) { AvroSchema.checkType("fatal", fatal, Boolean.class); AvroSchema.checkType("name", name, String.class); AvroSchema.checkType("description", description, String.class); AvroSchema.checkType("position", position, Long.class); BlobQueryError error = new BlobQueryError((Boolean) fatal, (String) name, (String) description, (Long) position); if (errorConsumer != null) { errorConsumer.accept(error); } else { return Mono.error(new IOException("An error was reported during query response processing, " + System.lineSeparator() + error.toString())); } } else { return Mono.error(new IllegalArgumentException("Failed to parse error record from " + "query response stream.")); } return Mono.empty(); } /** * Checks whether or not all parameters are non-null. */ private static boolean checkParametersNotNull(Object... data) { for (Object o : data) { if (o == null || o instanceof AvroNullSchema.Null) { return false; } } return true; } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformInputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryParquetSerialization) { generatedFormat.setType(QueryFormatType.PARQUET); generatedFormat.setParquetTextConfiguration(transformParquet( (BlobQueryParquetSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid input serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformOutputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryArrowSerialization) { generatedFormat.setType(QueryFormatType.ARROW); generatedFormat.setArrowConfiguration(transformArrow( (BlobQueryArrowSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid output serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a BlobQueryDelimitedSerialization into a DelimitedTextConfiguration. * * @param delimitedSerialization {@link BlobQueryDelimitedSerialization} * @return {@link DelimitedTextConfiguration} */ private static DelimitedTextConfiguration transformDelimited( BlobQueryDelimitedSerialization delimitedSerialization) { if (delimitedSerialization == null) { return null; } return new DelimitedTextConfiguration() .setColumnSeparator(charToString(delimitedSerialization.getColumnSeparator())) .setEscapeChar(charToString(delimitedSerialization.getEscapeChar())) .setFieldQuote(charToString(delimitedSerialization.getFieldQuote())) .setHeadersPresent(delimitedSerialization.isHeadersPresent()) .setRecordSeparator(charToString(delimitedSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryJsonSerialization into a JsonTextConfiguration. * * @param jsonSerialization {@link BlobQueryJsonSerialization} * @return {@link JsonTextConfiguration} */ private static JsonTextConfiguration transformJson(BlobQueryJsonSerialization jsonSerialization) { if (jsonSerialization == null) { return null; } return new JsonTextConfiguration() .setRecordSeparator(charToString(jsonSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryParquetSerialization into an Object. * * @param parquetSerialization {@link BlobQueryParquetSerialization} * @return {@link JsonTextConfiguration} */ private static Object transformParquet(BlobQueryParquetSerialization parquetSerialization) { /* This method returns an Object since the ParquetConfiguration currently accepts no options. This results in the generator generating ParquetConfiguration as an Object. */ if (parquetSerialization == null) { return null; } return new Object(); } /** * Transforms a BlobQueryArrowSerialization into a ArrowConfiguration. * * @param arrowSerialization {@link BlobQueryArrowSerialization} * @return {@link ArrowConfiguration} */ private static ArrowConfiguration transformArrow(BlobQueryArrowSerialization arrowSerialization) { if (arrowSerialization == null) { return null; } List<ArrowField> schema = arrowSerialization.getSchema() == null ? null : new ArrayList<>(arrowSerialization.getSchema().size()); if (schema != null) { for (BlobQueryArrowField field : arrowSerialization.getSchema()) { if (field == null) { schema.add(null); } else { schema.add(new ArrowField() .setName(field.getName()) .setPrecision(field.getPrecision()) .setScale(field.getScale()) .setType(field.getType().toString()) ); } } } return new ArrowConfiguration().setSchema(schema); } private static String charToString(char c) { return c == '\0' ? "" : Character.toString(c); } }
class BlobQueryReader { private static final ClientLogger LOGGER = new ClientLogger(BlobQueryReader.class); private final Flux<ByteBuffer> avro; private final Consumer<BlobQueryProgress> progressConsumer; private final Consumer<BlobQueryError> errorConsumer; /** * Creates a new BlobQueryReader. * * @param avro The reactive avro stream. * @param progressConsumer The progress consumer. * @param errorConsumer The error consumer. */ public BlobQueryReader(Flux<ByteBuffer> avro, Consumer<BlobQueryProgress> progressConsumer, Consumer<BlobQueryError> errorConsumer) { this.avro = avro; this.progressConsumer = progressConsumer; this.errorConsumer = errorConsumer; } /** * Avro parses a query reactive stream. * <p> * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @return The parsed query reactive stream. */ public Flux<ByteBuffer> read() { return new AvroReaderFactory().getAvroReader(avro).read() .map(AvroObject::getObject) .concatMap(this::parseRecord); } /** * Avro parses a query reactive stream. * * The Avro stream is formatted as the Avro Header (that specifies the schema) and the Avro Body (that contains * a series of blocks of data). The Query Avro schema indicates that the objects being emitted from the parser can * either be a result data record, an end record, a progress record or an error record. * * @param inputStream The input stream to read from. * @return The parsed query reactive stream. * @throws IOException If an I/O error occurs. */ private ByteBuffer convertInputStreamToByteBuffer(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] data = outputStream.toByteArray(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length); byteBuffer.put(data); byteBuffer.flip(); return byteBuffer; } private byte[] serializeAvroObjectsToBytes(Iterable<AvroObject> avroObjects) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (AvroObject avroObject : avroObjects) { try { Object potentialMap = avroObject.getObject(); if (!(potentialMap instanceof Map)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> recordMap = (Map<?, ?>) potentialMap; ByteBuffer buffer = parseSyncRecord(recordMap); if (buffer != null) { if (buffer.hasArray()) { outputStream.write(buffer.array(), buffer.position(), buffer.remaining()); } else { byte[] data = new byte[buffer.remaining()]; buffer.get(data); outputStream.write(data); } buffer.clear(); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } return outputStream.toByteArray(); } /** * Parses a query record. * * @param quickQueryRecord The query record. * @return The optional data in the record. */ private Mono<ByteBuffer> parseRecord(Object quickQueryRecord) { if (!(quickQueryRecord instanceof Map)) { return Mono.error(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> record = (Map<?, ?>) quickQueryRecord; Object recordSchema = record.get(AvroConstants.RECORD); switch (recordSchema.toString()) { case "resultData": return parseResultData(record); case "end": return parseEnd(record); case "progress": return parseProgress(record); case "error": return parseError(record); default: return Mono.error(new IllegalStateException(String.format("Unknown record type %s " + "while parsing query response. ", recordSchema.toString()))); } } /** * Parses a query record. * * @param quickQueryRecord The query record. * @return The optional data in the record. */ private ByteBuffer parseSyncRecord(Object quickQueryRecord) { if (!(quickQueryRecord instanceof Map)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Expected object to be of type Map")); } Map<?, ?> record = (Map<?, ?>) quickQueryRecord; Object recordSchema = record.get(AvroConstants.RECORD); switch (recordSchema.toString()) { case "resultData": return parseSyncResultData(record); case "end": return parseSyncEnd(record); case "progress": return parseSyncProgress(record); case "error": return parseSyncError(record); default: throw LOGGER.logExceptionAsError(new IllegalStateException(String.format("Unknown record type %s " + "while parsing query response. ", recordSchema.toString()))); } } /** * Parses a query result data record. * @param dataRecord The query result data record. * @return The data in the record. */ private Mono<ByteBuffer> parseResultData(Map<?, ?> dataRecord) { Object data = dataRecord.get("data"); if (checkParametersNotNull(data)) { AvroSchema.checkType("data", data, List.class); return Mono.just(ByteBuffer.wrap(AvroSchema.getBytes((List<?>) data))); } else { return Mono.error(new IllegalArgumentException("Failed to parse result data record from " + "query response stream.")); } } /** * Parses a query result data record. * @param dataRecord The query result data record. * @return The data in the record. */ private ByteBuffer parseSyncResultData(Map<?, ?> dataRecord) { Object data = dataRecord.get("data"); if (checkParametersNotNull(data)) { AvroSchema.checkType("data", data, List.class); return ByteBuffer.wrap(AvroSchema.getBytes((List<?>) data)); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse result data record from " + "query response stream.")); } } /** * Parses a query end record. * @param endRecord The query end record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseEnd(Map<?, ?> endRecord) { if (progressConsumer != null) { Object totalBytes = endRecord.get("totalBytes"); if (checkParametersNotNull(totalBytes)) { AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) totalBytes, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse end record from query " + "response stream.")); } } return Mono.empty(); } /** * Parses a query end record. * @param endRecord The query end record. * @return Mono.empty or Mono.error */ private ByteBuffer parseSyncEnd(Map<?, ?> endRecord) { if (progressConsumer != null) { Object totalBytes = endRecord.get("totalBytes"); if (checkParametersNotNull(totalBytes)) { AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) totalBytes, (long) totalBytes)); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse end record from query " + "response stream.")); } } return null; } /** * Parses a query progress record. * @param progressRecord The query progress record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseProgress(Map<?, ?> progressRecord) { if (progressConsumer != null) { Object bytesScanned = progressRecord.get("bytesScanned"); Object totalBytes = progressRecord.get("totalBytes"); if (checkParametersNotNull(bytesScanned, totalBytes)) { AvroSchema.checkType("bytesScanned", bytesScanned, Long.class); AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) bytesScanned, (long) totalBytes)); } else { return Mono.error(new IllegalArgumentException("Failed to parse progress record from " + "query response stream.")); } } return Mono.empty(); } /** * Parses a query progress record. * @param progressRecord The query progress record. * @return Mono.empty or Mono.error */ private ByteBuffer parseSyncProgress(Map<?, ?> progressRecord) { if (progressConsumer != null) { Object bytesScanned = progressRecord.get("bytesScanned"); Object totalBytes = progressRecord.get("totalBytes"); if (checkParametersNotNull(bytesScanned, totalBytes)) { AvroSchema.checkType("bytesScanned", bytesScanned, Long.class); AvroSchema.checkType("totalBytes", totalBytes, Long.class); progressConsumer.accept(new BlobQueryProgress((long) bytesScanned, (long) totalBytes)); } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse progress record from " + "query response stream.")); } } return null; } /** * Parses a query error record. * @param errorRecord The query error record. * @return Mono.empty or Mono.error */ private Mono<ByteBuffer> parseError(Map<?, ?> errorRecord) { Object fatal = errorRecord.get("fatal"); Object name = errorRecord.get("name"); Object description = errorRecord.get("description"); Object position = errorRecord.get("position"); if (checkParametersNotNull(fatal, name, description, position)) { AvroSchema.checkType("fatal", fatal, Boolean.class); AvroSchema.checkType("name", name, String.class); AvroSchema.checkType("description", description, String.class); AvroSchema.checkType("position", position, Long.class); BlobQueryError error = new BlobQueryError((Boolean) fatal, (String) name, (String) description, (Long) position); if (errorConsumer != null) { errorConsumer.accept(error); } else { return Mono.error(new IOException("An error was reported during query response processing, " + System.lineSeparator() + error.toString())); } } else { return Mono.error(new IllegalArgumentException("Failed to parse error record from " + "query response stream.")); } return Mono.empty(); } /** * Parses a query error record. * @param errorRecord The query error record. * @return Mono.empty or Mono.error */ private ByteBuffer parseSyncError(Map<?, ?> errorRecord) { Object fatal = errorRecord.get("fatal"); Object name = errorRecord.get("name"); Object description = errorRecord.get("description"); Object position = errorRecord.get("position"); if (checkParametersNotNull(fatal, name, description, position)) { AvroSchema.checkType("fatal", fatal, Boolean.class); AvroSchema.checkType("name", name, String.class); AvroSchema.checkType("description", description, String.class); AvroSchema.checkType("position", position, Long.class); BlobQueryError error = new BlobQueryError((Boolean) fatal, (String) name, (String) description, (Long) position); if (errorConsumer != null) { errorConsumer.accept(error); } else { throw LOGGER.logExceptionAsError(new UncheckedIOException(new IOException("An error was reported during query response processing, " + System.lineSeparator() + error.toString()))); } } else { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to parse error record from " + "query response stream.")); } return null; } /** * Checks whether or not all parameters are non-null. */ private static boolean checkParametersNotNull(Object... data) { for (Object o : data) { if (o == null || o instanceof AvroNullSchema.Null) { return false; } } return true; } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformInputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryParquetSerialization) { generatedFormat.setType(QueryFormatType.PARQUET); generatedFormat.setParquetTextConfiguration(transformParquet( (BlobQueryParquetSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid input serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a generic input BlobQuerySerialization into a QuerySerialization. * @param userSerialization {@link BlobQuerySerialization} * @param logger {@link ClientLogger} * @return {@link QuerySerialization} */ public static QuerySerialization transformOutputSerialization(BlobQuerySerialization userSerialization, ClientLogger logger) { if (userSerialization == null) { return null; } QueryFormat generatedFormat = new QueryFormat(); if (userSerialization instanceof BlobQueryDelimitedSerialization) { generatedFormat.setType(QueryFormatType.DELIMITED); generatedFormat.setDelimitedTextConfiguration(transformDelimited( (BlobQueryDelimitedSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryJsonSerialization) { generatedFormat.setType(QueryFormatType.JSON); generatedFormat.setJsonTextConfiguration(transformJson( (BlobQueryJsonSerialization) userSerialization)); } else if (userSerialization instanceof BlobQueryArrowSerialization) { generatedFormat.setType(QueryFormatType.ARROW); generatedFormat.setArrowConfiguration(transformArrow( (BlobQueryArrowSerialization) userSerialization)); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Please see values of valid output serialization in the documentation " + "(https: } return new QuerySerialization().setFormat(generatedFormat); } /** * Transforms a BlobQueryDelimitedSerialization into a DelimitedTextConfiguration. * * @param delimitedSerialization {@link BlobQueryDelimitedSerialization} * @return {@link DelimitedTextConfiguration} */ private static DelimitedTextConfiguration transformDelimited( BlobQueryDelimitedSerialization delimitedSerialization) { if (delimitedSerialization == null) { return null; } return new DelimitedTextConfiguration() .setColumnSeparator(charToString(delimitedSerialization.getColumnSeparator())) .setEscapeChar(charToString(delimitedSerialization.getEscapeChar())) .setFieldQuote(charToString(delimitedSerialization.getFieldQuote())) .setHeadersPresent(delimitedSerialization.isHeadersPresent()) .setRecordSeparator(charToString(delimitedSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryJsonSerialization into a JsonTextConfiguration. * * @param jsonSerialization {@link BlobQueryJsonSerialization} * @return {@link JsonTextConfiguration} */ private static JsonTextConfiguration transformJson(BlobQueryJsonSerialization jsonSerialization) { if (jsonSerialization == null) { return null; } return new JsonTextConfiguration() .setRecordSeparator(charToString(jsonSerialization.getRecordSeparator())); } /** * Transforms a BlobQueryParquetSerialization into an Object. * * @param parquetSerialization {@link BlobQueryParquetSerialization} * @return {@link JsonTextConfiguration} */ private static Object transformParquet(BlobQueryParquetSerialization parquetSerialization) { /* This method returns an Object since the ParquetConfiguration currently accepts no options. This results in the generator generating ParquetConfiguration as an Object. */ if (parquetSerialization == null) { return null; } return new Object(); } /** * Transforms a BlobQueryArrowSerialization into a ArrowConfiguration. * * @param arrowSerialization {@link BlobQueryArrowSerialization} * @return {@link ArrowConfiguration} */ private static ArrowConfiguration transformArrow(BlobQueryArrowSerialization arrowSerialization) { if (arrowSerialization == null) { return null; } List<ArrowField> schema = arrowSerialization.getSchema() == null ? null : new ArrayList<>(arrowSerialization.getSchema().size()); if (schema != null) { for (BlobQueryArrowField field : arrowSerialization.getSchema()) { if (field == null) { schema.add(null); } else { schema.add(new ArrowField() .setName(field.getName()) .setPrecision(field.getPrecision()) .setScale(field.getScale()) .setType(field.getType().toString()) ); } } } return new ArrowConfiguration().setSchema(schema); } private static String charToString(char c) { return c == '\0' ? "" : Character.toString(c); } }
is this because of spark? are customers seeing too many splits? I thought the reason for this `info` or even `warn` was to make sure customers are aware that splits are happening. Since splits are once in a while event.
private Flux<DocumentProducerFeedResponse> feedRangeGoneProof(Flux<DocumentProducerFeedResponse> sourceFeedResponseObservable) { return sourceFeedResponseObservable.onErrorResume( t -> { CosmosException dce = Utils.as(t, CosmosException.class); if (dce == null || !isSplitOrMerge(dce)) { logger.error( "Unexpected failure, Context: {}", this.operationContextTextProvider.get(), t); return Flux.error(t); } logger.debug( "DocumentProducer handling a partition gone in [{}], detail:[{}], Context: {}", feedRange, dce, this.operationContextTextProvider.get()); Mono<Utils.ValueHolder<List<PartitionKeyRange>>> replacementRangesObs = getReplacementRanges(feedRange.getRange()); Flux<DocumentProducer<T>> replacementProducers = replacementRangesObs.flux().flatMap( partitionKeyRangesValueHolder -> { if (partitionKeyRangesValueHolder == null || partitionKeyRangesValueHolder.v == null || partitionKeyRangesValueHolder.v.size() == 0) { logger.error("Failed to find at least one child range"); return Mono.error(new IllegalStateException("Failed to find at least one child range")); } if (partitionKeyRangesValueHolder.v.size() == 1) { if (logger.isInfoEnabled()) { logger.info( "Cross Partition Query Execution detected partition gone due to merge for feedRange [{}] with continuationToken [{}]", this.feedRange, lastResponseContinuationToken); } return Mono.just(this); } else { if (logger.isInfoEnabled()) { logger.info("Cross Partition Query Execution detected partition [{}] split into [{}] partitions," + " last continuation token is [{}]. - Context: {}", feedRange, partitionKeyRangesValueHolder.v.stream() .map(JsonSerializable::toJson) .collect(Collectors.joining(", ")), lastResponseContinuationToken, this.operationContextTextProvider.get()); } return Flux.fromIterable(createReplacingDocumentProducersOnSplit(partitionKeyRangesValueHolder.v)); } }); return produceOnFeedRangeGone(replacementProducers); }); }
logger.debug(
private Flux<DocumentProducerFeedResponse> feedRangeGoneProof(Flux<DocumentProducerFeedResponse> sourceFeedResponseObservable) { return sourceFeedResponseObservable.onErrorResume( t -> { CosmosException dce = Utils.as(t, CosmosException.class); if (dce == null || !isSplitOrMerge(dce)) { logger.error( "Unexpected failure, Context: {}", this.operationContextTextProvider.get(), t); return Flux.error(t); } logger.debug( "DocumentProducer handling a partition gone in [{}], detail:[{}], Context: {}", feedRange, dce, this.operationContextTextProvider.get()); Mono<Utils.ValueHolder<List<PartitionKeyRange>>> replacementRangesObs = getReplacementRanges(feedRange.getRange()); Flux<DocumentProducer<T>> replacementProducers = replacementRangesObs.flux().flatMap( partitionKeyRangesValueHolder -> { if (partitionKeyRangesValueHolder == null || partitionKeyRangesValueHolder.v == null || partitionKeyRangesValueHolder.v.size() == 0) { logger.error("Failed to find at least one child range"); return Mono.error(new IllegalStateException("Failed to find at least one child range")); } if (partitionKeyRangesValueHolder.v.size() == 1) { if (logger.isInfoEnabled()) { logger.info( "Cross Partition Query Execution detected partition gone due to merge for feedRange [{}] with continuationToken [{}]", this.feedRange, lastResponseContinuationToken); } return Mono.just(this); } else { if (logger.isInfoEnabled()) { logger.info("Cross Partition Query Execution detected partition [{}] split into [{}] partitions," + " last continuation token is [{}]. - Context: {}", feedRange, partitionKeyRangesValueHolder.v.stream() .map(JsonSerializable::toJson) .collect(Collectors.joining(", ")), lastResponseContinuationToken, this.operationContextTextProvider.get()); } return Flux.fromIterable(createReplacingDocumentProducersOnSplit(partitionKeyRangesValueHolder.v)); } }); return produceOnFeedRangeGone(replacementProducers); }); }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Collections.singletonList(schedulingTimeSpanMap) ), pageResult.getActivityId(), pageResult.getResponseHeaders().getOrDefault(HttpConstants.HttpHeaders.INDEX_UTILIZATION, null)); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Collections.singletonList(schedulingTimeSpanMap) ), pageResult.getActivityId(), pageResult.getResponseHeaders().getOrDefault(HttpConstants.HttpHeaders.INDEX_UTILIZATION, null)); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } } }
Not even hit in spark (spark queries are never cross partition). Same place is hit for any cross partition query to distribute the query across producers. It is not just happening when actual splits are happening. And Diagnostics have all the necessary info to debug. This INFO level log is not needed.
private Flux<DocumentProducerFeedResponse> feedRangeGoneProof(Flux<DocumentProducerFeedResponse> sourceFeedResponseObservable) { return sourceFeedResponseObservable.onErrorResume( t -> { CosmosException dce = Utils.as(t, CosmosException.class); if (dce == null || !isSplitOrMerge(dce)) { logger.error( "Unexpected failure, Context: {}", this.operationContextTextProvider.get(), t); return Flux.error(t); } logger.debug( "DocumentProducer handling a partition gone in [{}], detail:[{}], Context: {}", feedRange, dce, this.operationContextTextProvider.get()); Mono<Utils.ValueHolder<List<PartitionKeyRange>>> replacementRangesObs = getReplacementRanges(feedRange.getRange()); Flux<DocumentProducer<T>> replacementProducers = replacementRangesObs.flux().flatMap( partitionKeyRangesValueHolder -> { if (partitionKeyRangesValueHolder == null || partitionKeyRangesValueHolder.v == null || partitionKeyRangesValueHolder.v.size() == 0) { logger.error("Failed to find at least one child range"); return Mono.error(new IllegalStateException("Failed to find at least one child range")); } if (partitionKeyRangesValueHolder.v.size() == 1) { if (logger.isInfoEnabled()) { logger.info( "Cross Partition Query Execution detected partition gone due to merge for feedRange [{}] with continuationToken [{}]", this.feedRange, lastResponseContinuationToken); } return Mono.just(this); } else { if (logger.isInfoEnabled()) { logger.info("Cross Partition Query Execution detected partition [{}] split into [{}] partitions," + " last continuation token is [{}]. - Context: {}", feedRange, partitionKeyRangesValueHolder.v.stream() .map(JsonSerializable::toJson) .collect(Collectors.joining(", ")), lastResponseContinuationToken, this.operationContextTextProvider.get()); } return Flux.fromIterable(createReplacingDocumentProducersOnSplit(partitionKeyRangesValueHolder.v)); } }); return produceOnFeedRangeGone(replacementProducers); }); }
logger.debug(
private Flux<DocumentProducerFeedResponse> feedRangeGoneProof(Flux<DocumentProducerFeedResponse> sourceFeedResponseObservable) { return sourceFeedResponseObservable.onErrorResume( t -> { CosmosException dce = Utils.as(t, CosmosException.class); if (dce == null || !isSplitOrMerge(dce)) { logger.error( "Unexpected failure, Context: {}", this.operationContextTextProvider.get(), t); return Flux.error(t); } logger.debug( "DocumentProducer handling a partition gone in [{}], detail:[{}], Context: {}", feedRange, dce, this.operationContextTextProvider.get()); Mono<Utils.ValueHolder<List<PartitionKeyRange>>> replacementRangesObs = getReplacementRanges(feedRange.getRange()); Flux<DocumentProducer<T>> replacementProducers = replacementRangesObs.flux().flatMap( partitionKeyRangesValueHolder -> { if (partitionKeyRangesValueHolder == null || partitionKeyRangesValueHolder.v == null || partitionKeyRangesValueHolder.v.size() == 0) { logger.error("Failed to find at least one child range"); return Mono.error(new IllegalStateException("Failed to find at least one child range")); } if (partitionKeyRangesValueHolder.v.size() == 1) { if (logger.isInfoEnabled()) { logger.info( "Cross Partition Query Execution detected partition gone due to merge for feedRange [{}] with continuationToken [{}]", this.feedRange, lastResponseContinuationToken); } return Mono.just(this); } else { if (logger.isInfoEnabled()) { logger.info("Cross Partition Query Execution detected partition [{}] split into [{}] partitions," + " last continuation token is [{}]. - Context: {}", feedRange, partitionKeyRangesValueHolder.v.stream() .map(JsonSerializable::toJson) .collect(Collectors.joining(", ")), lastResponseContinuationToken, this.operationContextTextProvider.get()); } return Flux.fromIterable(createReplacingDocumentProducersOnSplit(partitionKeyRangesValueHolder.v)); } }); return produceOnFeedRangeGone(replacementProducers); }); }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Collections.singletonList(schedulingTimeSpanMap) ), pageResult.getActivityId(), pageResult.getResponseHeaders().getOrDefault(HttpConstants.HttpHeaders.INDEX_UTILIZATION, null)); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Collections.singletonList(schedulingTimeSpanMap) ), pageResult.getActivityId(), pageResult.getResponseHeaders().getOrDefault(HttpConstants.HttpHeaders.INDEX_UTILIZATION, null)); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } } }
Will this be a potential regression? What would have happened previously if a json payload somehow didn't have a family?
public static CloudServiceConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String family = null; String version = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("osFamily".equals(fieldName)) { family = reader.getString(); } else if ("osVersion".equals(fieldName)) { version = reader.getString(); } else { reader.skipChildren(); } } if (family != null) { return new CloudServiceConfiguration(family).setOsVersion(version); } else { return null; } }); }
return new CloudServiceConfiguration(family).setOsVersion(version);
public static CloudServiceConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String family = null; String version = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("osFamily".equals(fieldName)) { family = reader.getString(); } else if ("osVersion".equals(fieldName)) { version = reader.getString(); } else { reader.skipChildren(); } } return new CloudServiceConfiguration(family).setOsVersion(version); }); }
class CloudServiceConfiguration implements JsonSerializable<CloudServiceConfiguration> { /* * Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: */ @Generated private String osFamily; /* * The Azure Guest OS version to be installed on the virtual machines in the Pool. The default value is * which * specifies the latest operating system version for the specified OS family. */ @Generated private String osVersion; /** * Creates an instance of CloudServiceConfiguration class. * * @param osFamily the osFamily value to set. */ @Generated public CloudServiceConfiguration(String osFamily) { this.osFamily = osFamily; } /** * Get the osFamily property: Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: * * @return the osFamily value. */ @Generated public String getOsFamily() { return this.osFamily; } /** * Get the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @return the osVersion value. */ @Generated public String getOsVersion() { return this.osVersion; } /** * Set the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @param osVersion the osVersion value to set. * @return the CloudServiceConfiguration object itself. */ @Generated public CloudServiceConfiguration setOsVersion(String osVersion) { this.osVersion = osVersion; return this; } /** * Creates a representation of this object as JSON. * * @param jsonWriter Where the JSON representation is written to. * * @throws IOException Error while writing to JsonWriter. * @return The JsonWriter with the JSON representation of this object. */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("osFamily", osFamily); jsonWriter.writeStringField("osVersion", osVersion); jsonWriter.writeEndObject(); return jsonWriter; } /** * Creates a new instance from its JSON representation. * * @param jsonReader Where the JSON read from to deserialize the object. * * @throws IOException Error while reading from JsonReader. * @return Instance read from the JsonReader. */ }
class CloudServiceConfiguration implements JsonSerializable<CloudServiceConfiguration> { /* * Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: */ @Generated private String osFamily; /* * The Azure Guest OS version to be installed on the virtual machines in the Pool. The default value is * which * specifies the latest operating system version for the specified OS family. */ @Generated private String osVersion; /** * Creates an instance of CloudServiceConfiguration class. * * @param osFamily the osFamily value to set. */ @Generated public CloudServiceConfiguration(String osFamily) { this.osFamily = osFamily; } /** * Get the osFamily property: Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: * * @return the osFamily value. */ @Generated public String getOsFamily() { return this.osFamily; } /** * Get the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @return the osVersion value. */ @Generated public String getOsVersion() { return this.osVersion; } /** * Set the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @param osVersion the osVersion value to set. * @return the CloudServiceConfiguration object itself. */ @Generated public CloudServiceConfiguration setOsVersion(String osVersion) { this.osVersion = osVersion; return this; } /** * Creates a representation of this object as JSON. * * @param jsonWriter Where the JSON representation is written to. * * @throws IOException Error while writing to JsonWriter. * @return The JsonWriter with the JSON representation of this object. */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("osFamily", osFamily); jsonWriter.writeStringField("osVersion", osVersion); jsonWriter.writeEndObject(); return jsonWriter; } /** * Creates a new instance from its JSON representation. * * @param jsonReader Where the JSON read from to deserialize the object. * * @throws IOException Error while reading from JsonReader. * @return Instance read from the JsonReader. */ }
Urgh. Good find! :(
public static CloudServiceConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String family = null; String version = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("osFamily".equals(fieldName)) { family = reader.getString(); } else if ("osVersion".equals(fieldName)) { version = reader.getString(); } else { reader.skipChildren(); } } if (family != null) { return new CloudServiceConfiguration(family).setOsVersion(version); } else { return null; } }); }
return new CloudServiceConfiguration(family).setOsVersion(version);
public static CloudServiceConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String family = null; String version = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("osFamily".equals(fieldName)) { family = reader.getString(); } else if ("osVersion".equals(fieldName)) { version = reader.getString(); } else { reader.skipChildren(); } } return new CloudServiceConfiguration(family).setOsVersion(version); }); }
class CloudServiceConfiguration implements JsonSerializable<CloudServiceConfiguration> { /* * Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: */ @Generated private String osFamily; /* * The Azure Guest OS version to be installed on the virtual machines in the Pool. The default value is * which * specifies the latest operating system version for the specified OS family. */ @Generated private String osVersion; /** * Creates an instance of CloudServiceConfiguration class. * * @param osFamily the osFamily value to set. */ @Generated public CloudServiceConfiguration(String osFamily) { this.osFamily = osFamily; } /** * Get the osFamily property: Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: * * @return the osFamily value. */ @Generated public String getOsFamily() { return this.osFamily; } /** * Get the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @return the osVersion value. */ @Generated public String getOsVersion() { return this.osVersion; } /** * Set the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @param osVersion the osVersion value to set. * @return the CloudServiceConfiguration object itself. */ @Generated public CloudServiceConfiguration setOsVersion(String osVersion) { this.osVersion = osVersion; return this; } /** * Creates a representation of this object as JSON. * * @param jsonWriter Where the JSON representation is written to. * * @throws IOException Error while writing to JsonWriter. * @return The JsonWriter with the JSON representation of this object. */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("osFamily", osFamily); jsonWriter.writeStringField("osVersion", osVersion); jsonWriter.writeEndObject(); return jsonWriter; } /** * Creates a new instance from its JSON representation. * * @param jsonReader Where the JSON read from to deserialize the object. * * @throws IOException Error while reading from JsonReader. * @return Instance read from the JsonReader. */ }
class CloudServiceConfiguration implements JsonSerializable<CloudServiceConfiguration> { /* * Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: */ @Generated private String osFamily; /* * The Azure Guest OS version to be installed on the virtual machines in the Pool. The default value is * which * specifies the latest operating system version for the specified OS family. */ @Generated private String osVersion; /** * Creates an instance of CloudServiceConfiguration class. * * @param osFamily the osFamily value to set. */ @Generated public CloudServiceConfiguration(String osFamily) { this.osFamily = osFamily; } /** * Get the osFamily property: Possible values are: * 2 - OS Family 2, equivalent to Windows Server 2008 R2 * SP1. * 3 - OS Family 3, equivalent to Windows Server 2012. * 4 - OS Family 4, * equivalent to Windows Server 2012 R2. * 5 - OS Family 5, equivalent to Windows * Server 2016. * 6 - OS Family 6, equivalent to Windows Server 2019. For more * information, see Azure Guest OS Releases * (https: * * @return the osFamily value. */ @Generated public String getOsFamily() { return this.osFamily; } /** * Get the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @return the osVersion value. */ @Generated public String getOsVersion() { return this.osVersion; } /** * Set the osVersion property: The Azure Guest OS version to be installed on the virtual machines in the Pool. The * default value is * which specifies the latest operating system version for the specified OS family. * * @param osVersion the osVersion value to set. * @return the CloudServiceConfiguration object itself. */ @Generated public CloudServiceConfiguration setOsVersion(String osVersion) { this.osVersion = osVersion; return this; } /** * Creates a representation of this object as JSON. * * @param jsonWriter Where the JSON representation is written to. * * @throws IOException Error while writing to JsonWriter. * @return The JsonWriter with the JSON representation of this object. */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("osFamily", osFamily); jsonWriter.writeStringField("osVersion", osVersion); jsonWriter.writeEndObject(); return jsonWriter; } /** * Creates a new instance from its JSON representation. * * @param jsonReader Where the JSON read from to deserialize the object. * * @throws IOException Error while reading from JsonReader. * @return Instance read from the JsonReader. */ }
same as in other file, if user wants it printed, they can do it themselves, we should not print stack traces
public Response<RemoveParticipantsResult> removeParticipantsWithResponse(String roomId, Iterable<CommunicationIdentifier> identifiers, Context context) { try { context = context == null ? Context.NONE : context; Objects.requireNonNull(identifiers, "'identifiers' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomIdentifiersToMapForRemove( identifiers); String updateRequest = getUpdateRequest(participantMap); Response<Object> response = this.participantsClient .updateWithResponse(roomId, updateRequest, context); return new SimpleResponse<RemoveParticipantsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } catch (IOException ex) { ex.printStackTrace(); throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } }
ex.printStackTrace();
public Response<RemoveParticipantsResult> removeParticipantsWithResponse(String roomId, Iterable<CommunicationIdentifier> identifiers, Context context) { try { context = context == null ? Context.NONE : context; Objects.requireNonNull(identifiers, "'identifiers' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomIdentifiersToMapForRemove( identifiers); String updateRequest = getUpdateRequest(participantMap); Response<Object> response = this.participantsClient .updateWithResponse(roomId, updateRequest, context); return new SimpleResponse<RemoveParticipantsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } catch (IOException ex) { throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } }
class RoomsClient { private final RoomsImpl roomsClient; private final ParticipantsImpl participantsClient; private final ClientLogger logger = new ClientLogger(RoomsClient.class); RoomsClient(AzureCommunicationRoomServiceImpl roomsServiceClient) { roomsClient = roomsServiceClient.getRooms(); participantsClient = roomsServiceClient.getParticipants(); } /** * Create a new room. Input field is nullable. * * @param createRoomOptions the create room options. * @return response for a successful create room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRoom createRoom(CreateRoomOptions createRoomOptions) { RoomModel roomModel = this.roomsClient .create(toCreateRoomRequest(createRoomOptions.getValidFrom(), createRoomOptions.getValidUntil(), createRoomOptions.isPstnDialOutEnabled(), createRoomOptions.getParticipants())); return getCommunicationRoomFromResponse(roomModel); } /** * Create a new Room with response. * * @param createRoomOptions the create room options. * @param context The context of key value pairs for http request. * @return response for a successful create room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CommunicationRoom> createRoomWithResponse(CreateRoomOptions createRoomOptions, Context context) { context = context == null ? Context.NONE : context; Response<RoomModel> response = this.roomsClient .createWithResponse(toCreateRoomRequest(createRoomOptions.getValidFrom(), createRoomOptions.getValidUntil(), createRoomOptions.isPstnDialOutEnabled(), createRoomOptions.getParticipants()), context); return new SimpleResponse<CommunicationRoom>(response, getCommunicationRoomFromResponse(response.getValue())); } /** * Update an existing Room. * * @param roomId The room Id. * @param updateRoomOptions the update room options. * @return response for a successful update room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRoom updateRoom(String roomId, UpdateRoomOptions updateRoomOptions) { RoomModel roomModel = this.roomsClient .update(roomId, toUpdateRoomRequest(updateRoomOptions.getValidFrom(), updateRoomOptions.getValidUntil(), updateRoomOptions.isPstnDialOutEnabled())); return getCommunicationRoomFromResponse(roomModel); } /** * Update an existing Room with response. * * @param roomId The room Id. * @param updateRoomOptions the update room options. * @param context The context of key value pairs for http request. * @return response for a successful update room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CommunicationRoom> updateRoomWithResponse(String roomId, UpdateRoomOptions updateRoomOptions, Context context) { context = context == null ? Context.NONE : context; Response<RoomModel> response = this.roomsClient .updateWithResponse(roomId, toUpdateRoomRequest(updateRoomOptions.getValidFrom(), updateRoomOptions.getValidUntil(), updateRoomOptions.isPstnDialOutEnabled()), context); return new SimpleResponse<CommunicationRoom>(response, getCommunicationRoomFromResponse(response.getValue())); } /** * Get an existing room. * * @param roomId The room id. * @return The existing room. */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRoom getRoom(String roomId) { RoomModel roomModel = this.roomsClient .get(roomId); return getCommunicationRoomFromResponse(roomModel); } /** * Get an existing room with response. * * @param roomId The room id. * @param context The context of key value pairs for http request. * @return The existing room. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CommunicationRoom> getRoomWithResponse(String roomId, Context context) { context = context == null ? Context.NONE : context; Response<RoomModel> response = this.roomsClient .getWithResponse(roomId, context); return new SimpleResponse<CommunicationRoom>(response, getCommunicationRoomFromResponse(response.getValue())); } /** * Delete an existing room. * * @param roomId The room Id. */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteRoom(String roomId) { this.roomsClient.delete(roomId); } /** * Delete an existing room. * * @param roomId The room Id. * @param context The context of key value pairs for http request. * @return Response with status code only. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteRoomWithResponse(String roomId, Context context) { context = context == null ? Context.NONE : context; return this.roomsClient.deleteWithResponse(roomId, context); } /** * Lists all rooms. * * @return The existing rooms. */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<CommunicationRoom> listRooms() { return new PagedIterable<>( () -> this.roomsClient.listSinglePage(), nextLink -> this.roomsClient.listNextSinglePage(nextLink)) .mapPage(f -> RoomModelConverter.convert(f)); } /** * Lists all rooms. * * @param context The context of key value pairs for http request. * @return The existing rooms. */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<CommunicationRoom> listRooms(Context context) { final Context serviceContext = context == null ? Context.NONE : context; return new PagedIterable<>( () -> this.roomsClient.listSinglePage(serviceContext), nextLink -> this.roomsClient.listNextSinglePage(nextLink, serviceContext)) .mapPage(f -> RoomModelConverter.convert(f)); } /** * addOrUpdate participants to an existing Room. * * @param roomId The room id. * @param participants The participants list. * @return response for a successful addOrUpdate participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public AddOrUpdateParticipantsResult addOrUpdateParticipants(String roomId, Iterable<RoomParticipant> participants) { try { Objects.requireNonNull(participants, "'participants' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomParticipantsToMapForAddOrUpdate(participants); String updateRequest = getUpdateRequest(participantMap); this.participantsClient.update(roomId, updateRequest); return new AddOrUpdateParticipantsResult(); } catch (IOException ex) { ex.printStackTrace(); throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } } /** * addOrUpdate participants to an existing Room with response * * @param roomId The room id. * @param participants The participants list. * @param context The context of key value pairs for http request. * @return response for a successful addOrUpdate participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<AddOrUpdateParticipantsResult> addOrUpdateParticipantsWithResponse(String roomId, Iterable<RoomParticipant> participants, Context context) { try { context = context == null ? Context.NONE : context; Objects.requireNonNull(participants, "'participants' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomParticipantsToMapForAddOrUpdate(participants); String updateRequest = getUpdateRequest(participantMap); Response<Object> response = this.participantsClient .updateWithResponse(roomId, updateRequest, context); return new SimpleResponse<AddOrUpdateParticipantsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } catch (IOException ex) { ex.printStackTrace(); throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } } /** * Remove participants to an existing Room. * * @param roomId The room id. * @param identifiers The communication identifiers list. * @return response for a successful remove participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public RemoveParticipantsResult removeParticipants(String roomId, Iterable<CommunicationIdentifier> identifiers) { try { Objects.requireNonNull(identifiers, "'identifiers' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomIdentifiersToMapForRemove( identifiers); String updateRequest = getUpdateRequest(participantMap); this.participantsClient.update(roomId, updateRequest); return new RemoveParticipantsResult(); } catch (IOException ex) { ex.printStackTrace(); throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } } /** * Remove participants to an existing Room with response * * @param roomId The room id. * @param identifiers The communication identifiers list. * @param context The context of key value pairs for http request. * @return response for a successful remove participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * List Room participants. * * @param roomId The room id. * @return Room Participants List */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<RoomParticipant> listParticipants(String roomId) { Objects.requireNonNull(roomId, "'roomId' cannot be null."); return new PagedIterable<>( () -> this.participantsClient.listSinglePage(roomId), nextLink -> this.participantsClient.listNextSinglePage(nextLink)) .mapPage(f -> RoomParticipantConverter.convert(f)); } /** * List Room participants. * * @param roomId The room id. * @param context The context of key value pairs for http request. * @return Room Participants List */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<RoomParticipant> listParticipants(String roomId, Context context) { final Context serviceContext = context == null ? Context.NONE : context; Objects.requireNonNull(roomId, "'roomId' cannot be null."); return new PagedIterable<>( () -> this.participantsClient.listSinglePage(roomId, serviceContext), nextLink -> this.participantsClient.listNextSinglePage(nextLink, serviceContext)) .mapPage(f -> RoomParticipantConverter.convert(f)); } private CommunicationRoom getCommunicationRoomFromResponse(RoomModel room) { return new CommunicationRoom( room.getId(), room.getValidFrom(), room.getValidUntil(), room.getCreatedAt(), room.isPstnDialOutEnabled()); } /** * Translate to create room request. * * @return The create room request. */ private CreateRoomRequest toCreateRoomRequest(OffsetDateTime validFrom, OffsetDateTime validUntil, Boolean pstnDialOutEnabled, Iterable<RoomParticipant> participants) { CreateRoomRequest createRoomRequest = new CreateRoomRequest(); if (validFrom != null) { createRoomRequest.setValidFrom(validFrom); } if (validUntil != null) { createRoomRequest.setValidUntil(validUntil); } if (pstnDialOutEnabled != null) { createRoomRequest.setPstnDialOutEnabled(pstnDialOutEnabled); } Map<String, ParticipantProperties> roomParticipants = new HashMap<>(); if (participants != null) { roomParticipants = convertRoomParticipantsToMapForAddOrUpdate(participants); } if (participants != null) { createRoomRequest.setParticipants(roomParticipants); } return createRoomRequest; } /** * Translate to update room request. * * @return The update room request. */ private UpdateRoomRequest toUpdateRoomRequest(OffsetDateTime validFrom, OffsetDateTime validUntil, Boolean isPstnDialOutEnabled) { UpdateRoomRequest updateRoomRequest = new UpdateRoomRequest(); if (validFrom != null) { updateRoomRequest.setValidFrom(validFrom); } if (validUntil != null) { updateRoomRequest.setValidUntil(validUntil); } if (isPstnDialOutEnabled != null) { updateRoomRequest.setPstnDialOutEnabled(isPstnDialOutEnabled); } return updateRoomRequest; } /** * Translate to map for add or update participants. * * @return Map of participants. */ private Map<String, ParticipantProperties> convertRoomParticipantsToMapForAddOrUpdate( Iterable<RoomParticipant> participants) { Map<String, ParticipantProperties> participantMap = new HashMap<>(); if (participants != null) { for (RoomParticipant participant : participants) { participantMap.put(participant.getCommunicationIdentifier().getRawId(), new ParticipantProperties().setRole(ParticipantRoleConverter.convert(participant.getRole()))); } } return participantMap; } /** * Translate to map for remove participants. * * @return Map of participants. */ private Map<String, ParticipantProperties> convertRoomIdentifiersToMapForRemove( Iterable<CommunicationIdentifier> identifiers) { Map<String, ParticipantProperties> participantMap = new HashMap<>(); if (identifiers != null) { for (CommunicationIdentifier identifier : identifiers) { participantMap.put(identifier.getRawId(), null); } } return participantMap; } private static String getUpdateRequest(Map<String, ParticipantProperties> participantMap) throws IOException { Writer json = new StringWriter(); try (JsonWriter jsonWriter = JsonProviders.createWriter(json)) { new UpdateParticipantsRequest().setParticipants(participantMap).toJson(jsonWriter); } return json.toString(); } }
class RoomsClient { private final RoomsImpl roomsClient; private final ParticipantsImpl participantsClient; private final ClientLogger logger = new ClientLogger(RoomsClient.class); RoomsClient(AzureCommunicationRoomServiceImpl roomsServiceClient) { roomsClient = roomsServiceClient.getRooms(); participantsClient = roomsServiceClient.getParticipants(); } /** * Create a new room. Input field is nullable. * * @param createRoomOptions the create room options. * @return response for a successful create room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRoom createRoom(CreateRoomOptions createRoomOptions) { RoomModel roomModel = this.roomsClient .create(toCreateRoomRequest(createRoomOptions.getValidFrom(), createRoomOptions.getValidUntil(), createRoomOptions.isPstnDialOutEnabled(), createRoomOptions.getParticipants())); return getCommunicationRoomFromResponse(roomModel); } /** * Create a new Room with response. * * @param createRoomOptions the create room options. * @param context The context of key value pairs for http request. * @return response for a successful create room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CommunicationRoom> createRoomWithResponse(CreateRoomOptions createRoomOptions, Context context) { context = context == null ? Context.NONE : context; Response<RoomModel> response = this.roomsClient .createWithResponse(toCreateRoomRequest(createRoomOptions.getValidFrom(), createRoomOptions.getValidUntil(), createRoomOptions.isPstnDialOutEnabled(), createRoomOptions.getParticipants()), context); return new SimpleResponse<CommunicationRoom>(response, getCommunicationRoomFromResponse(response.getValue())); } /** * Update an existing Room. * * @param roomId The room Id. * @param updateRoomOptions the update room options. * @return response for a successful update room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRoom updateRoom(String roomId, UpdateRoomOptions updateRoomOptions) { RoomModel roomModel = this.roomsClient .update(roomId, toUpdateRoomRequest(updateRoomOptions.getValidFrom(), updateRoomOptions.getValidUntil(), updateRoomOptions.isPstnDialOutEnabled())); return getCommunicationRoomFromResponse(roomModel); } /** * Update an existing Room with response. * * @param roomId The room Id. * @param updateRoomOptions the update room options. * @param context The context of key value pairs for http request. * @return response for a successful update room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CommunicationRoom> updateRoomWithResponse(String roomId, UpdateRoomOptions updateRoomOptions, Context context) { context = context == null ? Context.NONE : context; Response<RoomModel> response = this.roomsClient .updateWithResponse(roomId, toUpdateRoomRequest(updateRoomOptions.getValidFrom(), updateRoomOptions.getValidUntil(), updateRoomOptions.isPstnDialOutEnabled()), context); return new SimpleResponse<CommunicationRoom>(response, getCommunicationRoomFromResponse(response.getValue())); } /** * Get an existing room. * * @param roomId The room id. * @return The existing room. */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRoom getRoom(String roomId) { RoomModel roomModel = this.roomsClient .get(roomId); return getCommunicationRoomFromResponse(roomModel); } /** * Get an existing room with response. * * @param roomId The room id. * @param context The context of key value pairs for http request. * @return The existing room. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CommunicationRoom> getRoomWithResponse(String roomId, Context context) { context = context == null ? Context.NONE : context; Response<RoomModel> response = this.roomsClient .getWithResponse(roomId, context); return new SimpleResponse<CommunicationRoom>(response, getCommunicationRoomFromResponse(response.getValue())); } /** * Delete an existing room. * * @param roomId The room Id. */ @ServiceMethod(returns = ReturnType.SINGLE) public void deleteRoom(String roomId) { this.roomsClient.delete(roomId); } /** * Delete an existing room. * * @param roomId The room Id. * @param context The context of key value pairs for http request. * @return Response with status code only. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> deleteRoomWithResponse(String roomId, Context context) { context = context == null ? Context.NONE : context; return this.roomsClient.deleteWithResponse(roomId, context); } /** * Lists all rooms. * * @return The existing rooms. */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<CommunicationRoom> listRooms() { return new PagedIterable<>( () -> this.roomsClient.listSinglePage(), nextLink -> this.roomsClient.listNextSinglePage(nextLink)) .mapPage(f -> RoomModelConverter.convert(f)); } /** * Lists all rooms. * * @param context The context of key value pairs for http request. * @return The existing rooms. */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<CommunicationRoom> listRooms(Context context) { final Context serviceContext = context == null ? Context.NONE : context; return new PagedIterable<>( () -> this.roomsClient.listSinglePage(serviceContext), nextLink -> this.roomsClient.listNextSinglePage(nextLink, serviceContext)) .mapPage(f -> RoomModelConverter.convert(f)); } /** * addOrUpdate participants to an existing Room. * * @param roomId The room id. * @param participants The participants list. * @return response for a successful addOrUpdate participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public AddOrUpdateParticipantsResult addOrUpdateParticipants(String roomId, Iterable<RoomParticipant> participants) { try { Objects.requireNonNull(participants, "'participants' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomParticipantsToMapForAddOrUpdate(participants); String updateRequest = getUpdateRequest(participantMap); this.participantsClient.update(roomId, updateRequest); return new AddOrUpdateParticipantsResult(); } catch (IOException ex) { throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } } /** * addOrUpdate participants to an existing Room with response * * @param roomId The room id. * @param participants The participants list. * @param context The context of key value pairs for http request. * @return response for a successful addOrUpdate participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<AddOrUpdateParticipantsResult> addOrUpdateParticipantsWithResponse(String roomId, Iterable<RoomParticipant> participants, Context context) { try { context = context == null ? Context.NONE : context; Objects.requireNonNull(participants, "'participants' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomParticipantsToMapForAddOrUpdate(participants); String updateRequest = getUpdateRequest(participantMap); Response<Object> response = this.participantsClient .updateWithResponse(roomId, updateRequest, context); return new SimpleResponse<AddOrUpdateParticipantsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } catch (IOException ex) { throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } } /** * Remove participants to an existing Room. * * @param roomId The room id. * @param identifiers The communication identifiers list. * @return response for a successful remove participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) public RemoveParticipantsResult removeParticipants(String roomId, Iterable<CommunicationIdentifier> identifiers) { try { Objects.requireNonNull(identifiers, "'identifiers' cannot be null."); Objects.requireNonNull(roomId, "'roomId' cannot be null."); Map<String, ParticipantProperties> participantMap = convertRoomIdentifiersToMapForRemove( identifiers); String updateRequest = getUpdateRequest(participantMap); this.participantsClient.update(roomId, updateRequest); return new RemoveParticipantsResult(); } catch (IOException ex) { throw logger.logExceptionAsError(new IllegalArgumentException("Failed to process JSON input", ex)); } } /** * Remove participants to an existing Room with response * * @param roomId The room id. * @param identifiers The communication identifiers list. * @param context The context of key value pairs for http request. * @return response for a successful remove participants room request. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * List Room participants. * * @param roomId The room id. * @return Room Participants List */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<RoomParticipant> listParticipants(String roomId) { Objects.requireNonNull(roomId, "'roomId' cannot be null."); return new PagedIterable<>( () -> this.participantsClient.listSinglePage(roomId), nextLink -> this.participantsClient.listNextSinglePage(nextLink)) .mapPage(f -> RoomParticipantConverter.convert(f)); } /** * List Room participants. * * @param roomId The room id. * @param context The context of key value pairs for http request. * @return Room Participants List */ @ServiceMethod(returns = ReturnType.SINGLE) public PagedIterable<RoomParticipant> listParticipants(String roomId, Context context) { final Context serviceContext = context == null ? Context.NONE : context; Objects.requireNonNull(roomId, "'roomId' cannot be null."); return new PagedIterable<>( () -> this.participantsClient.listSinglePage(roomId, serviceContext), nextLink -> this.participantsClient.listNextSinglePage(nextLink, serviceContext)) .mapPage(f -> RoomParticipantConverter.convert(f)); } }
Invalid constructor call for GetTokenForTeamsUserOptions . edit: Manually updated cc: @alzimmermsft
public static GetTokenForTeamsUserOptions fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { GetTokenForTeamsUserOptions deserializedTeamsUserExchangeTokenRequest = new GetTokenForTeamsUserOptions(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("token".equals(fieldName)) { deserializedTeamsUserExchangeTokenRequest.teamsUserAadToken = reader.getString(); } else if ("appId".equals(fieldName)) { deserializedTeamsUserExchangeTokenRequest.clientId = reader.getString(); } else if ("userId".equals(fieldName)) { deserializedTeamsUserExchangeTokenRequest.userObjectId = reader.getString(); } else { reader.skipChildren(); } } return deserializedTeamsUserExchangeTokenRequest; }); }
GetTokenForTeamsUserOptions deserializedTeamsUserExchangeTokenRequest = new GetTokenForTeamsUserOptions();
public static GetTokenForTeamsUserOptions fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String teamsUserAadToken = null; String clientId = null; String userObjectId = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("token".equals(fieldName)) { teamsUserAadToken = reader.getString(); } else if ("appId".equals(fieldName)) { clientId = reader.getString(); } else if ("userId".equals(fieldName)) { userObjectId = reader.getString(); } else { reader.skipChildren(); } } return new GetTokenForTeamsUserOptions(teamsUserAadToken, clientId, userObjectId); }); }
class GetTokenForTeamsUserOptions implements JsonSerializable<GetTokenForTeamsUserOptions> { /* * Azure AD access token of a Teams User to acquire a new Communication Identity access token. */ private String teamsUserAadToken; /* * Client ID of an Azure AD application to be verified against the appid claim in the Azure AD access token. */ private String clientId; /* * Object ID of an Azure AD user (Teams User) to be verified against the oid claim in the Azure AD access token. */ private String userObjectId; /** * Constructor of {@link GetTokenForTeamsUserOptions}. * * @param teamsUserAadToken Azure AD access token of a Teams User. * @param clientId Client ID of an Azure AD application to be verified against the appId claim in the Azure AD * access token. * @param userObjectId Object ID of an Azure AD user (Teams User) to be verified against the OID claim in the Azure * AD access token. */ public GetTokenForTeamsUserOptions(String teamsUserAadToken, String clientId, String userObjectId) { this.teamsUserAadToken = teamsUserAadToken; this.clientId = clientId; this.userObjectId = userObjectId; } /** * Gets the Azure AD access token of a Teams User. * * @return the Azure AD access token of a Teams User. */ public String getTeamsUserAadToken() { return this.teamsUserAadToken; } /** * Gets the Client ID of an Azure AD application. * * @return the Client ID of an Azure AD application. */ public String getClientId() { return this.clientId; } /** * Gets the Object ID of an Azure AD user (Teams User). * * @return the Object ID of an Azure AD user (Teams User). */ public String getUserObjectId() { return this.userObjectId; } @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("token", this.teamsUserAadToken); jsonWriter.writeStringField("appId", this.clientId); jsonWriter.writeStringField("userId", this.userObjectId); return jsonWriter.writeEndObject(); } /** * Reads an instance of TeamsUserExchangeTokenRequest from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of TeamsUserExchangeTokenRequest if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the TeamsUserExchangeTokenRequest. */ }
class GetTokenForTeamsUserOptions implements JsonSerializable<GetTokenForTeamsUserOptions> { /* * Azure AD access token of a Teams User to acquire a new Communication Identity access token. */ private String teamsUserAadToken; /* * Client ID of an Azure AD application to be verified against the appid claim in the Azure AD access token. */ private String clientId; /* * Object ID of an Azure AD user (Teams User) to be verified against the oid claim in the Azure AD access token. */ private String userObjectId; /** * Constructor of {@link GetTokenForTeamsUserOptions}. * * @param teamsUserAadToken Azure AD access token of a Teams User. * @param clientId Client ID of an Azure AD application to be verified against the appId claim in the Azure AD * access token. * @param userObjectId Object ID of an Azure AD user (Teams User) to be verified against the OID claim in the Azure * AD access token. */ public GetTokenForTeamsUserOptions(String teamsUserAadToken, String clientId, String userObjectId) { this.teamsUserAadToken = teamsUserAadToken; this.clientId = clientId; this.userObjectId = userObjectId; } /** * Gets the Azure AD access token of a Teams User. * * @return the Azure AD access token of a Teams User. */ public String getTeamsUserAadToken() { return this.teamsUserAadToken; } /** * Gets the Client ID of an Azure AD application. * * @return the Client ID of an Azure AD application. */ public String getClientId() { return this.clientId; } /** * Gets the Object ID of an Azure AD user (Teams User). * * @return the Object ID of an Azure AD user (Teams User). */ public String getUserObjectId() { return this.userObjectId; } @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("token", this.teamsUserAadToken); jsonWriter.writeStringField("appId", this.clientId); jsonWriter.writeStringField("userId", this.userObjectId); return jsonWriter.writeEndObject(); } /** * Reads an instance of TeamsUserExchangeTokenRequest from the JsonReader. * * @param jsonReader The JsonReader being read. * @return An instance of TeamsUserExchangeTokenRequest if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the TeamsUserExchangeTokenRequest. */ }
@alzimmermsft is this is expected?
private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithAllProperties() { String value = "{\"code\":\"Error Code\",\"message\":\"Error Message\",\"target\":\"Error Target\",\"details\":[{\"code\":\"New Error Code\",\"message\":\"New Error Message\"}]}"; CommunicationError communicationError = new CommunicationError().setCode("Error Code").setMessage("Error Message"); CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); }
private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithAllProperties() { String value = "{\"code\":\"Error Code\",\"message\":\"Error Message\",\"target\":\"Error Target\",\"details\":[{\"code\":\"New Error Code\",\"message\":\"New Error Message\"}]}"; CommunicationError communicationError; try (JsonReader jsonReader = JsonProviders.createReader(value)) { communicationError = CommunicationError.fromJson(jsonReader); } catch (IOException e) { throw new RuntimeException(e); } CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); }
class IdentityErrorConverterUnitTests { private HttpResponse httpResponse; private CommunicationErrorResponseException communicationResponseException; @BeforeEach public void setUp() { httpResponse = new MockHttpResponse(null, 0); } @AfterEach public void destroy() { httpResponse = null; communicationResponseException = null; } @Test public void translateExceptionWithAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNotNull(identityResponseException.getValue().getTarget()); assertFalse(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithoutAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNull(identityResponseException.getValue().getTarget()); assertTrue(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutErrorResponse() { communicationResponseException = new CommunicationErrorResponseException("Exception Message", httpResponse); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertNull(identityResponseException.getValue()); } private void assertIdentityResponseExceptionMandates(IdentityErrorResponseException identityResponseException) { assertNotNull(identityResponseException); assertEquals(communicationResponseException.getMessage(), identityResponseException.getMessage()); assertEquals(communicationResponseException.getResponse(), identityResponseException.getResponse()); } private void assertIdentityErrorMandates(IdentityError identityError) { assertEquals(communicationResponseException.getValue().getError().getCode(), identityError.getCode()); assertEquals(communicationResponseException.getValue().getError().getMessage(), identityError.getMessage()); } private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithoutAllProperties() { CommunicationError communicationError = new CommunicationError().setCode("Error Code").setMessage("Error Message"); CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); } }
class IdentityErrorConverterUnitTests { private HttpResponse httpResponse; private CommunicationErrorResponseException communicationResponseException; @BeforeEach public void setUp() { httpResponse = new MockHttpResponse(null, 0); } @AfterEach public void destroy() { httpResponse = null; communicationResponseException = null; } @Test public void translateExceptionWithAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNotNull(identityResponseException.getValue().getTarget()); assertFalse(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithoutAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNull(identityResponseException.getValue().getTarget()); assertTrue(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutErrorResponse() { communicationResponseException = new CommunicationErrorResponseException("Exception Message", httpResponse); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertNull(identityResponseException.getValue()); } private void assertIdentityResponseExceptionMandates(IdentityErrorResponseException identityResponseException) { assertNotNull(identityResponseException); assertEquals(communicationResponseException.getMessage(), identityResponseException.getMessage()); assertEquals(communicationResponseException.getResponse(), identityResponseException.getResponse()); } private void assertIdentityErrorMandates(IdentityError identityError) { assertEquals(communicationResponseException.getValue().getError().getCode(), identityError.getCode()); assertEquals(communicationResponseException.getValue().getError().getMessage(), identityError.getMessage()); } private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithoutAllProperties() { CommunicationError communicationError = new CommunicationError().setCode("Error Code").setMessage("Error Message"); CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); } }
Yes, but this is a case where you'd want to switch over the test code to using ```java try (JsonReader jsonReader = JsonProviders.createReader(value)) { communicationError = CommunicationError.fromJson(jsonReader); } ``` to have the stream-style deserialization method handle setting the values that are read-only (aka, cannot be set with a public API). This is the equivalent of what was being done with Jackson Databind before but using azure-json APIs.
private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithAllProperties() { String value = "{\"code\":\"Error Code\",\"message\":\"Error Message\",\"target\":\"Error Target\",\"details\":[{\"code\":\"New Error Code\",\"message\":\"New Error Message\"}]}"; CommunicationError communicationError = new CommunicationError().setCode("Error Code").setMessage("Error Message"); CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); }
private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithAllProperties() { String value = "{\"code\":\"Error Code\",\"message\":\"Error Message\",\"target\":\"Error Target\",\"details\":[{\"code\":\"New Error Code\",\"message\":\"New Error Message\"}]}"; CommunicationError communicationError; try (JsonReader jsonReader = JsonProviders.createReader(value)) { communicationError = CommunicationError.fromJson(jsonReader); } catch (IOException e) { throw new RuntimeException(e); } CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); }
class IdentityErrorConverterUnitTests { private HttpResponse httpResponse; private CommunicationErrorResponseException communicationResponseException; @BeforeEach public void setUp() { httpResponse = new MockHttpResponse(null, 0); } @AfterEach public void destroy() { httpResponse = null; communicationResponseException = null; } @Test public void translateExceptionWithAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNotNull(identityResponseException.getValue().getTarget()); assertFalse(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithoutAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNull(identityResponseException.getValue().getTarget()); assertTrue(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutErrorResponse() { communicationResponseException = new CommunicationErrorResponseException("Exception Message", httpResponse); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertNull(identityResponseException.getValue()); } private void assertIdentityResponseExceptionMandates(IdentityErrorResponseException identityResponseException) { assertNotNull(identityResponseException); assertEquals(communicationResponseException.getMessage(), identityResponseException.getMessage()); assertEquals(communicationResponseException.getResponse(), identityResponseException.getResponse()); } private void assertIdentityErrorMandates(IdentityError identityError) { assertEquals(communicationResponseException.getValue().getError().getCode(), identityError.getCode()); assertEquals(communicationResponseException.getValue().getError().getMessage(), identityError.getMessage()); } private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithoutAllProperties() { CommunicationError communicationError = new CommunicationError().setCode("Error Code").setMessage("Error Message"); CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); } }
class IdentityErrorConverterUnitTests { private HttpResponse httpResponse; private CommunicationErrorResponseException communicationResponseException; @BeforeEach public void setUp() { httpResponse = new MockHttpResponse(null, 0); } @AfterEach public void destroy() { httpResponse = null; communicationResponseException = null; } @Test public void translateExceptionWithAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNotNull(identityResponseException.getValue().getTarget()); assertFalse(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutAllPropertiesSet() { communicationResponseException = setUpCommunicationResponseExceptionWithoutAllProperties(); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertIdentityErrorMandates(identityResponseException.getValue()); assertNull(identityResponseException.getValue().getTarget()); assertTrue(identityResponseException.getValue().getDetails().isEmpty()); } @Test public void translateExceptionWithoutErrorResponse() { communicationResponseException = new CommunicationErrorResponseException("Exception Message", httpResponse); IdentityErrorResponseException identityResponseException = IdentityErrorConverter.translateException(communicationResponseException); assertIdentityResponseExceptionMandates(identityResponseException); assertNull(identityResponseException.getValue()); } private void assertIdentityResponseExceptionMandates(IdentityErrorResponseException identityResponseException) { assertNotNull(identityResponseException); assertEquals(communicationResponseException.getMessage(), identityResponseException.getMessage()); assertEquals(communicationResponseException.getResponse(), identityResponseException.getResponse()); } private void assertIdentityErrorMandates(IdentityError identityError) { assertEquals(communicationResponseException.getValue().getError().getCode(), identityError.getCode()); assertEquals(communicationResponseException.getValue().getError().getMessage(), identityError.getMessage()); } private CommunicationErrorResponseException setUpCommunicationResponseExceptionWithoutAllProperties() { CommunicationError communicationError = new CommunicationError().setCode("Error Code").setMessage("Error Message"); CommunicationErrorResponse errorResponse = new CommunicationErrorResponse().setError(communicationError); return new CommunicationErrorResponseException("Exception Message", httpResponse, errorResponse); } }
Few more thoughts: - Should a null `key` throw an error? - Instead of substring when the `key` starts with `KEY_PREFIX` we should instead add the `KEY_PREFIX` if it doesn't start with the `KEY_PREFIX`. ```java // TODO: Determine if key == null should throw an exception if (key != null && !key.startsWith(KEY_PREFIX)) { super.setKey(KEY_PREFIX + key); } else { super.setKey(key); } return this; ```
public FeatureFlagConfigurationSetting setKey(String key) { if (key != null && key.startsWith(FeatureFlagConfigurationSetting.KEY_PREFIX)) { key = key.substring(FeatureFlagConfigurationSetting.KEY_PREFIX.length()); } super.setKey(KEY_PREFIX + key); return this; }
if (key != null && key.startsWith(FeatureFlagConfigurationSetting.KEY_PREFIX)) {
public FeatureFlagConfigurationSetting setKey(String key) { if (key != null && !key.startsWith(KEY_PREFIX)) { super.setKey(KEY_PREFIX + key); } else { super.setKey(key); } return this; }
class FeatureFlagConfigurationSetting extends ConfigurationSetting { private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class); private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8"; /** * A prefix is used to construct a feature flag configuration setting's key. */ public static final String KEY_PREFIX = ".appconfig.featureflag/"; private String featureId; private boolean isEnabled; private String description; private String displayName; private List<FeatureFlagFilter> clientFilters; private boolean isValidFeatureFlagValue; private final Map<String, Object> parsedProperties = new LinkedHashMap<>(5); private final List<String> requiredJsonProperties = Arrays.asList(ID, ENABLED, CONDITIONS); private final List<String> requiredOrOptionalJsonProperties = Arrays.asList(ID, DESCRIPTION, DISPLAY_NAME, ENABLED, CONDITIONS); /** * The constructor for a feature flag configuration setting. * * @param featureId A feature flag identification value that used to construct in setting's key. The key of setting * is {@code KEY_PREFIX} concatenate {@code featureId}. * @param isEnabled A boolean value to turn on/off the feature flag setting. */ public FeatureFlagConfigurationSetting(String featureId, boolean isEnabled) { isValidFeatureFlagValue = true; this.featureId = featureId; this.isEnabled = isEnabled; super.setKey(KEY_PREFIX + featureId); super.setContentType(FEATURE_FLAG_CONTENT_TYPE); } @Override public String getValue() { String newValue = null; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonWriter writer = JsonProviders.createWriter(outputStream); final Set<String> knownProperties = new LinkedHashSet<>(requiredOrOptionalJsonProperties); writer.writeStartObject(); for (Map.Entry<String, Object> entry : parsedProperties.entrySet()) { final String name = entry.getKey(); final Object jsonValue = entry.getValue(); try { if (tryWriteKnownProperty(name, jsonValue, writer, true)) { knownProperties.remove(name); } else { writer.writeUntypedField(name, jsonValue); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } for (final String propertyName : knownProperties) { tryWriteKnownProperty(propertyName, null, writer, false); } writer.writeEndObject(); writer.flush(); newValue = outputStream.toString(StandardCharsets.UTF_8.name()); outputStream.close(); } catch (IOException exception) { LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value.", exception)); } super.setValue(newValue); return newValue; } /** * Sets the key of this setting. * * @param key The key to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override /** * Sets the value of this setting. * * @param value The value to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ @Override public FeatureFlagConfigurationSetting setValue(String value) { tryParseValue(value); isValidFeatureFlagValue = true; super.setValue(value); return this; } /** * Sets the label of this configuration setting. {@link * set. * * @param label The label of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setLabel(String label) { super.setLabel(label); return this; } /** * Sets the content type. By default, the content type is null. * * @param contentType The content type of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setContentType(String contentType) { super.setContentType(contentType); return this; } /** * Sets the ETag for this configuration setting. * * @param etag The ETag for the configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setETag(String etag) { super.setETag(etag); return this; } /** * Sets the tags for this configuration setting. * * @param tags The tags to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setTags(Map<String, String> tags) { super.setTags(tags); return this; } /** * Get the feature ID of this configuration setting. * * @return the feature ID of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getFeatureId() { checkValid(); return featureId; } /** * Set the feature ID of this configuration setting. * * @param featureId the feature ID of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setFeatureId(String featureId) { checkValid(); this.featureId = featureId; super.setKey(KEY_PREFIX + featureId); return this; } /** * Get the boolean indicator to show if the setting is turn on or off. * * @return the boolean indicator to show if the setting is turn on or off. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public boolean isEnabled() { checkValid(); return this.isEnabled; } /** * Set the boolean indicator to show if the setting is turn on or off. * * @param isEnabled the boolean indicator to show if the setting is turn on or off. * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setEnabled(boolean isEnabled) { checkValid(); this.isEnabled = isEnabled; return this; } /** * Get the description of this configuration setting. * * @return the description of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDescription() { checkValid(); return description; } /** * Set the description of this configuration setting. * * @param description the description of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDescription(String description) { checkValid(); this.description = description; return this; } /** * Get the display name of this configuration setting. * * @return the display name of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDisplayName() { checkValid(); return displayName; } /** * Set the display name of this configuration setting. * * @param displayName the display name of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDisplayName(String displayName) { checkValid(); this.displayName = displayName; return this; } /** * Gets the feature flag filters of this configuration setting. * * @return the feature flag filters of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public List<FeatureFlagFilter> getClientFilters() { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } return clientFilters; } /** * Sets the feature flag filters of this configuration setting. * * @param clientFilters the feature flag filters of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setClientFilters(List<FeatureFlagFilter> clientFilters) { checkValid(); this.clientFilters = clientFilters; return this; } /** * Add a feature flag filter to this configuration setting. * * @param clientFilter a feature flag filter to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting addClientFilter(FeatureFlagFilter clientFilter) { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } clientFilters.add(clientFilter); return this; } private void checkValid() { if (!isValidFeatureFlagValue) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The content of the " + super.getValue() + " property do not represent a valid feature flag configuration setting.")); } } private boolean tryWriteKnownProperty(String propertyName, Object propertyValue, JsonWriter writer, boolean includeOptionalWhenNull) throws IOException { switch (propertyName) { case ID: writer.writeStringField(ID, featureId); break; case DESCRIPTION: if (includeOptionalWhenNull || description != null) { writer.writeStringField(DESCRIPTION, description); } break; case DISPLAY_NAME: if (includeOptionalWhenNull || displayName != null) { writer.writeStringField(DISPLAY_NAME, displayName); } break; case ENABLED: writer.writeBooleanField(ENABLED, isEnabled); break; case CONDITIONS: tryWriteConditions(propertyValue, writer); break; default: return false; } return true; } private void tryWriteConditions(Object propertyValue, JsonWriter writer) throws IOException { writer.writeStartObject(CONDITIONS); if (propertyValue != null && propertyValue instanceof Conditions) { Conditions propertyValueClone = (Conditions) propertyValue; for (Map.Entry<String, Object> entry : propertyValueClone.getUnknownConditions().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); writer.writeUntypedField(key, value); } } writer.writeArrayField(CLIENT_FILTERS, this.clientFilters, (jsonWriter, filter) -> { jsonWriter.writeStartObject(); jsonWriter.writeStringField(NAME, filter.getName()); jsonWriter.writeMapField(PARAMETERS, filter.getParameters(), JsonWriter::writeUntyped); jsonWriter.writeEndObject(); }); writer.writeEndObject(); } private void tryParseValue(String value) { parsedProperties.clear(); try (JsonReader jsonReader = JsonProviders.createReader(value)) { jsonReader.readObject(reader -> { final Set<String> requiredPropertiesCopy = new LinkedHashSet<>(requiredJsonProperties); String featureIdCopy = this.featureId; String descriptionCopy = this.description; String displayNameCopy = this.displayName; boolean isEnabledCopy = this.isEnabled; List<FeatureFlagFilter> featureFlagFiltersCopy = this.clientFilters; while (reader.nextToken() != JsonToken.END_OBJECT) { final String fieldName = reader.getFieldName(); reader.nextToken(); if (ID.equals(fieldName)) { final String id = reader.getString(); featureIdCopy = id; parsedProperties.put(ID, id); } else if (DESCRIPTION.equals(fieldName)) { final String description = reader.getString(); descriptionCopy = description; parsedProperties.put(DESCRIPTION, description); } else if (DISPLAY_NAME.equals(fieldName)) { final String displayName = reader.getString(); displayNameCopy = displayName; parsedProperties.put(DISPLAY_NAME, displayName); } else if (ENABLED.equals(fieldName)) { final boolean isEnabled = reader.getBoolean(); isEnabledCopy = isEnabled; parsedProperties.put(ENABLED, isEnabled); } else if (CONDITIONS.equals(fieldName)) { final Conditions conditions = readConditions(reader); if (conditions != null) { List<FeatureFlagFilter> featureFlagFilters = conditions.getFeatureFlagFilters(); featureFlagFiltersCopy = featureFlagFilters; parsedProperties.put(CONDITIONS, conditions); } } else { parsedProperties.put(fieldName, reader.readUntyped()); } requiredPropertiesCopy.remove(fieldName); } this.featureId = featureIdCopy; this.description = descriptionCopy; this.displayName = displayNameCopy; this.isEnabled = isEnabledCopy; this.clientFilters = featureFlagFiltersCopy; return requiredPropertiesCopy.isEmpty(); }); } catch (IOException e) { isValidFeatureFlagValue = false; throw LOGGER.logExceptionAsError(new IllegalArgumentException(e)); } } }
class FeatureFlagConfigurationSetting extends ConfigurationSetting { private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class); private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8"; /** * A prefix is used to construct a feature flag configuration setting's key. */ public static final String KEY_PREFIX = ".appconfig.featureflag/"; private String featureId; private boolean isEnabled; private String description; private String displayName; private List<FeatureFlagFilter> clientFilters; private boolean isValidFeatureFlagValue; private final Map<String, Object> parsedProperties = new LinkedHashMap<>(5); private final List<String> requiredJsonProperties = Arrays.asList(ID, ENABLED, CONDITIONS); private final List<String> requiredOrOptionalJsonProperties = Arrays.asList(ID, DESCRIPTION, DISPLAY_NAME, ENABLED, CONDITIONS); /** * The constructor for a feature flag configuration setting. * * @param featureId A feature flag identification value that used to construct in setting's key. The key of setting * is {@code KEY_PREFIX} concatenate {@code featureId}. * @param isEnabled A boolean value to turn on/off the feature flag setting. */ public FeatureFlagConfigurationSetting(String featureId, boolean isEnabled) { isValidFeatureFlagValue = true; this.featureId = featureId; this.isEnabled = isEnabled; super.setKey(KEY_PREFIX + featureId); super.setContentType(FEATURE_FLAG_CONTENT_TYPE); } @Override public String getValue() { String newValue = null; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonWriter writer = JsonProviders.createWriter(outputStream); final Set<String> knownProperties = new LinkedHashSet<>(requiredOrOptionalJsonProperties); writer.writeStartObject(); for (Map.Entry<String, Object> entry : parsedProperties.entrySet()) { final String name = entry.getKey(); final Object jsonValue = entry.getValue(); try { if (tryWriteKnownProperty(name, jsonValue, writer, true)) { knownProperties.remove(name); } else { writer.writeUntypedField(name, jsonValue); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } for (final String propertyName : knownProperties) { tryWriteKnownProperty(propertyName, null, writer, false); } writer.writeEndObject(); writer.flush(); newValue = outputStream.toString(StandardCharsets.UTF_8.name()); outputStream.close(); } catch (IOException exception) { LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value.", exception)); } super.setValue(newValue); return newValue; } /** * Sets the key of this setting. * * @param key The key to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override /** * Sets the value of this setting. * * @param value The value to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ @Override public FeatureFlagConfigurationSetting setValue(String value) { tryParseValue(value); isValidFeatureFlagValue = true; super.setValue(value); return this; } /** * Sets the label of this configuration setting. {@link * set. * * @param label The label of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setLabel(String label) { super.setLabel(label); return this; } /** * Sets the content type. By default, the content type is null. * * @param contentType The content type of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setContentType(String contentType) { super.setContentType(contentType); return this; } /** * Sets the ETag for this configuration setting. * * @param etag The ETag for the configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setETag(String etag) { super.setETag(etag); return this; } /** * Sets the tags for this configuration setting. * * @param tags The tags to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setTags(Map<String, String> tags) { super.setTags(tags); return this; } /** * Get the feature ID of this configuration setting. * * @return the feature ID of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getFeatureId() { checkValid(); return featureId; } /** * Set the feature ID of this configuration setting. * * @param featureId the feature ID of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setFeatureId(String featureId) { checkValid(); this.featureId = featureId; super.setKey(KEY_PREFIX + featureId); return this; } /** * Get the boolean indicator to show if the setting is turn on or off. * * @return the boolean indicator to show if the setting is turn on or off. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public boolean isEnabled() { checkValid(); return this.isEnabled; } /** * Set the boolean indicator to show if the setting is turn on or off. * * @param isEnabled the boolean indicator to show if the setting is turn on or off. * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setEnabled(boolean isEnabled) { checkValid(); this.isEnabled = isEnabled; return this; } /** * Get the description of this configuration setting. * * @return the description of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDescription() { checkValid(); return description; } /** * Set the description of this configuration setting. * * @param description the description of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDescription(String description) { checkValid(); this.description = description; return this; } /** * Get the display name of this configuration setting. * * @return the display name of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDisplayName() { checkValid(); return displayName; } /** * Set the display name of this configuration setting. * * @param displayName the display name of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDisplayName(String displayName) { checkValid(); this.displayName = displayName; return this; } /** * Gets the feature flag filters of this configuration setting. * * @return the feature flag filters of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public List<FeatureFlagFilter> getClientFilters() { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } return clientFilters; } /** * Sets the feature flag filters of this configuration setting. * * @param clientFilters the feature flag filters of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setClientFilters(List<FeatureFlagFilter> clientFilters) { checkValid(); this.clientFilters = clientFilters; return this; } /** * Add a feature flag filter to this configuration setting. * * @param clientFilter a feature flag filter to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting addClientFilter(FeatureFlagFilter clientFilter) { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } clientFilters.add(clientFilter); return this; } private void checkValid() { if (!isValidFeatureFlagValue) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The content of the " + super.getValue() + " property do not represent a valid feature flag configuration setting.")); } } private boolean tryWriteKnownProperty(String propertyName, Object propertyValue, JsonWriter writer, boolean includeOptionalWhenNull) throws IOException { switch (propertyName) { case ID: writer.writeStringField(ID, featureId); break; case DESCRIPTION: if (includeOptionalWhenNull || description != null) { writer.writeStringField(DESCRIPTION, description); } break; case DISPLAY_NAME: if (includeOptionalWhenNull || displayName != null) { writer.writeStringField(DISPLAY_NAME, displayName); } break; case ENABLED: writer.writeBooleanField(ENABLED, isEnabled); break; case CONDITIONS: tryWriteConditions(propertyValue, writer); break; default: return false; } return true; } private void tryWriteConditions(Object propertyValue, JsonWriter writer) throws IOException { writer.writeStartObject(CONDITIONS); if (propertyValue != null && propertyValue instanceof Conditions) { Conditions propertyValueClone = (Conditions) propertyValue; for (Map.Entry<String, Object> entry : propertyValueClone.getUnknownConditions().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); writer.writeUntypedField(key, value); } } writer.writeArrayField(CLIENT_FILTERS, this.clientFilters, (jsonWriter, filter) -> { jsonWriter.writeStartObject(); jsonWriter.writeStringField(NAME, filter.getName()); jsonWriter.writeMapField(PARAMETERS, filter.getParameters(), JsonWriter::writeUntyped); jsonWriter.writeEndObject(); }); writer.writeEndObject(); } private void tryParseValue(String value) { parsedProperties.clear(); try (JsonReader jsonReader = JsonProviders.createReader(value)) { jsonReader.readObject(reader -> { final Set<String> requiredPropertiesCopy = new LinkedHashSet<>(requiredJsonProperties); String featureIdCopy = this.featureId; String descriptionCopy = this.description; String displayNameCopy = this.displayName; boolean isEnabledCopy = this.isEnabled; List<FeatureFlagFilter> featureFlagFiltersCopy = this.clientFilters; while (reader.nextToken() != JsonToken.END_OBJECT) { final String fieldName = reader.getFieldName(); reader.nextToken(); if (ID.equals(fieldName)) { final String id = reader.getString(); featureIdCopy = id; parsedProperties.put(ID, id); } else if (DESCRIPTION.equals(fieldName)) { final String description = reader.getString(); descriptionCopy = description; parsedProperties.put(DESCRIPTION, description); } else if (DISPLAY_NAME.equals(fieldName)) { final String displayName = reader.getString(); displayNameCopy = displayName; parsedProperties.put(DISPLAY_NAME, displayName); } else if (ENABLED.equals(fieldName)) { final boolean isEnabled = reader.getBoolean(); isEnabledCopy = isEnabled; parsedProperties.put(ENABLED, isEnabled); } else if (CONDITIONS.equals(fieldName)) { final Conditions conditions = readConditions(reader); if (conditions != null) { List<FeatureFlagFilter> featureFlagFilters = conditions.getFeatureFlagFilters(); featureFlagFiltersCopy = featureFlagFilters; parsedProperties.put(CONDITIONS, conditions); } } else { parsedProperties.put(fieldName, reader.readUntyped()); } requiredPropertiesCopy.remove(fieldName); } this.featureId = featureIdCopy; this.description = descriptionCopy; this.displayName = displayNameCopy; this.isEnabled = isEnabledCopy; this.clientFilters = featureFlagFiltersCopy; return requiredPropertiesCopy.isEmpty(); }); } catch (IOException e) { isValidFeatureFlagValue = false; throw LOGGER.logExceptionAsError(new IllegalArgumentException(e)); } } }
`key` is required and cannot be null. But we don't do client-side validation
public FeatureFlagConfigurationSetting setKey(String key) { if (key != null && key.startsWith(FeatureFlagConfigurationSetting.KEY_PREFIX)) { key = key.substring(FeatureFlagConfigurationSetting.KEY_PREFIX.length()); } super.setKey(KEY_PREFIX + key); return this; }
if (key != null && key.startsWith(FeatureFlagConfigurationSetting.KEY_PREFIX)) {
public FeatureFlagConfigurationSetting setKey(String key) { if (key != null && !key.startsWith(KEY_PREFIX)) { super.setKey(KEY_PREFIX + key); } else { super.setKey(key); } return this; }
class FeatureFlagConfigurationSetting extends ConfigurationSetting { private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class); private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8"; /** * A prefix is used to construct a feature flag configuration setting's key. */ public static final String KEY_PREFIX = ".appconfig.featureflag/"; private String featureId; private boolean isEnabled; private String description; private String displayName; private List<FeatureFlagFilter> clientFilters; private boolean isValidFeatureFlagValue; private final Map<String, Object> parsedProperties = new LinkedHashMap<>(5); private final List<String> requiredJsonProperties = Arrays.asList(ID, ENABLED, CONDITIONS); private final List<String> requiredOrOptionalJsonProperties = Arrays.asList(ID, DESCRIPTION, DISPLAY_NAME, ENABLED, CONDITIONS); /** * The constructor for a feature flag configuration setting. * * @param featureId A feature flag identification value that used to construct in setting's key. The key of setting * is {@code KEY_PREFIX} concatenate {@code featureId}. * @param isEnabled A boolean value to turn on/off the feature flag setting. */ public FeatureFlagConfigurationSetting(String featureId, boolean isEnabled) { isValidFeatureFlagValue = true; this.featureId = featureId; this.isEnabled = isEnabled; super.setKey(KEY_PREFIX + featureId); super.setContentType(FEATURE_FLAG_CONTENT_TYPE); } @Override public String getValue() { String newValue = null; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonWriter writer = JsonProviders.createWriter(outputStream); final Set<String> knownProperties = new LinkedHashSet<>(requiredOrOptionalJsonProperties); writer.writeStartObject(); for (Map.Entry<String, Object> entry : parsedProperties.entrySet()) { final String name = entry.getKey(); final Object jsonValue = entry.getValue(); try { if (tryWriteKnownProperty(name, jsonValue, writer, true)) { knownProperties.remove(name); } else { writer.writeUntypedField(name, jsonValue); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } for (final String propertyName : knownProperties) { tryWriteKnownProperty(propertyName, null, writer, false); } writer.writeEndObject(); writer.flush(); newValue = outputStream.toString(StandardCharsets.UTF_8.name()); outputStream.close(); } catch (IOException exception) { LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value.", exception)); } super.setValue(newValue); return newValue; } /** * Sets the key of this setting. * * @param key The key to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override /** * Sets the value of this setting. * * @param value The value to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ @Override public FeatureFlagConfigurationSetting setValue(String value) { tryParseValue(value); isValidFeatureFlagValue = true; super.setValue(value); return this; } /** * Sets the label of this configuration setting. {@link * set. * * @param label The label of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setLabel(String label) { super.setLabel(label); return this; } /** * Sets the content type. By default, the content type is null. * * @param contentType The content type of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setContentType(String contentType) { super.setContentType(contentType); return this; } /** * Sets the ETag for this configuration setting. * * @param etag The ETag for the configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setETag(String etag) { super.setETag(etag); return this; } /** * Sets the tags for this configuration setting. * * @param tags The tags to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setTags(Map<String, String> tags) { super.setTags(tags); return this; } /** * Get the feature ID of this configuration setting. * * @return the feature ID of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getFeatureId() { checkValid(); return featureId; } /** * Set the feature ID of this configuration setting. * * @param featureId the feature ID of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setFeatureId(String featureId) { checkValid(); this.featureId = featureId; super.setKey(KEY_PREFIX + featureId); return this; } /** * Get the boolean indicator to show if the setting is turn on or off. * * @return the boolean indicator to show if the setting is turn on or off. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public boolean isEnabled() { checkValid(); return this.isEnabled; } /** * Set the boolean indicator to show if the setting is turn on or off. * * @param isEnabled the boolean indicator to show if the setting is turn on or off. * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setEnabled(boolean isEnabled) { checkValid(); this.isEnabled = isEnabled; return this; } /** * Get the description of this configuration setting. * * @return the description of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDescription() { checkValid(); return description; } /** * Set the description of this configuration setting. * * @param description the description of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDescription(String description) { checkValid(); this.description = description; return this; } /** * Get the display name of this configuration setting. * * @return the display name of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDisplayName() { checkValid(); return displayName; } /** * Set the display name of this configuration setting. * * @param displayName the display name of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDisplayName(String displayName) { checkValid(); this.displayName = displayName; return this; } /** * Gets the feature flag filters of this configuration setting. * * @return the feature flag filters of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public List<FeatureFlagFilter> getClientFilters() { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } return clientFilters; } /** * Sets the feature flag filters of this configuration setting. * * @param clientFilters the feature flag filters of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setClientFilters(List<FeatureFlagFilter> clientFilters) { checkValid(); this.clientFilters = clientFilters; return this; } /** * Add a feature flag filter to this configuration setting. * * @param clientFilter a feature flag filter to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting addClientFilter(FeatureFlagFilter clientFilter) { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } clientFilters.add(clientFilter); return this; } private void checkValid() { if (!isValidFeatureFlagValue) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The content of the " + super.getValue() + " property do not represent a valid feature flag configuration setting.")); } } private boolean tryWriteKnownProperty(String propertyName, Object propertyValue, JsonWriter writer, boolean includeOptionalWhenNull) throws IOException { switch (propertyName) { case ID: writer.writeStringField(ID, featureId); break; case DESCRIPTION: if (includeOptionalWhenNull || description != null) { writer.writeStringField(DESCRIPTION, description); } break; case DISPLAY_NAME: if (includeOptionalWhenNull || displayName != null) { writer.writeStringField(DISPLAY_NAME, displayName); } break; case ENABLED: writer.writeBooleanField(ENABLED, isEnabled); break; case CONDITIONS: tryWriteConditions(propertyValue, writer); break; default: return false; } return true; } private void tryWriteConditions(Object propertyValue, JsonWriter writer) throws IOException { writer.writeStartObject(CONDITIONS); if (propertyValue != null && propertyValue instanceof Conditions) { Conditions propertyValueClone = (Conditions) propertyValue; for (Map.Entry<String, Object> entry : propertyValueClone.getUnknownConditions().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); writer.writeUntypedField(key, value); } } writer.writeArrayField(CLIENT_FILTERS, this.clientFilters, (jsonWriter, filter) -> { jsonWriter.writeStartObject(); jsonWriter.writeStringField(NAME, filter.getName()); jsonWriter.writeMapField(PARAMETERS, filter.getParameters(), JsonWriter::writeUntyped); jsonWriter.writeEndObject(); }); writer.writeEndObject(); } private void tryParseValue(String value) { parsedProperties.clear(); try (JsonReader jsonReader = JsonProviders.createReader(value)) { jsonReader.readObject(reader -> { final Set<String> requiredPropertiesCopy = new LinkedHashSet<>(requiredJsonProperties); String featureIdCopy = this.featureId; String descriptionCopy = this.description; String displayNameCopy = this.displayName; boolean isEnabledCopy = this.isEnabled; List<FeatureFlagFilter> featureFlagFiltersCopy = this.clientFilters; while (reader.nextToken() != JsonToken.END_OBJECT) { final String fieldName = reader.getFieldName(); reader.nextToken(); if (ID.equals(fieldName)) { final String id = reader.getString(); featureIdCopy = id; parsedProperties.put(ID, id); } else if (DESCRIPTION.equals(fieldName)) { final String description = reader.getString(); descriptionCopy = description; parsedProperties.put(DESCRIPTION, description); } else if (DISPLAY_NAME.equals(fieldName)) { final String displayName = reader.getString(); displayNameCopy = displayName; parsedProperties.put(DISPLAY_NAME, displayName); } else if (ENABLED.equals(fieldName)) { final boolean isEnabled = reader.getBoolean(); isEnabledCopy = isEnabled; parsedProperties.put(ENABLED, isEnabled); } else if (CONDITIONS.equals(fieldName)) { final Conditions conditions = readConditions(reader); if (conditions != null) { List<FeatureFlagFilter> featureFlagFilters = conditions.getFeatureFlagFilters(); featureFlagFiltersCopy = featureFlagFilters; parsedProperties.put(CONDITIONS, conditions); } } else { parsedProperties.put(fieldName, reader.readUntyped()); } requiredPropertiesCopy.remove(fieldName); } this.featureId = featureIdCopy; this.description = descriptionCopy; this.displayName = displayNameCopy; this.isEnabled = isEnabledCopy; this.clientFilters = featureFlagFiltersCopy; return requiredPropertiesCopy.isEmpty(); }); } catch (IOException e) { isValidFeatureFlagValue = false; throw LOGGER.logExceptionAsError(new IllegalArgumentException(e)); } } }
class FeatureFlagConfigurationSetting extends ConfigurationSetting { private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class); private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8"; /** * A prefix is used to construct a feature flag configuration setting's key. */ public static final String KEY_PREFIX = ".appconfig.featureflag/"; private String featureId; private boolean isEnabled; private String description; private String displayName; private List<FeatureFlagFilter> clientFilters; private boolean isValidFeatureFlagValue; private final Map<String, Object> parsedProperties = new LinkedHashMap<>(5); private final List<String> requiredJsonProperties = Arrays.asList(ID, ENABLED, CONDITIONS); private final List<String> requiredOrOptionalJsonProperties = Arrays.asList(ID, DESCRIPTION, DISPLAY_NAME, ENABLED, CONDITIONS); /** * The constructor for a feature flag configuration setting. * * @param featureId A feature flag identification value that used to construct in setting's key. The key of setting * is {@code KEY_PREFIX} concatenate {@code featureId}. * @param isEnabled A boolean value to turn on/off the feature flag setting. */ public FeatureFlagConfigurationSetting(String featureId, boolean isEnabled) { isValidFeatureFlagValue = true; this.featureId = featureId; this.isEnabled = isEnabled; super.setKey(KEY_PREFIX + featureId); super.setContentType(FEATURE_FLAG_CONTENT_TYPE); } @Override public String getValue() { String newValue = null; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonWriter writer = JsonProviders.createWriter(outputStream); final Set<String> knownProperties = new LinkedHashSet<>(requiredOrOptionalJsonProperties); writer.writeStartObject(); for (Map.Entry<String, Object> entry : parsedProperties.entrySet()) { final String name = entry.getKey(); final Object jsonValue = entry.getValue(); try { if (tryWriteKnownProperty(name, jsonValue, writer, true)) { knownProperties.remove(name); } else { writer.writeUntypedField(name, jsonValue); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } for (final String propertyName : knownProperties) { tryWriteKnownProperty(propertyName, null, writer, false); } writer.writeEndObject(); writer.flush(); newValue = outputStream.toString(StandardCharsets.UTF_8.name()); outputStream.close(); } catch (IOException exception) { LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value.", exception)); } super.setValue(newValue); return newValue; } /** * Sets the key of this setting. * * @param key The key to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override /** * Sets the value of this setting. * * @param value The value to associate with this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ @Override public FeatureFlagConfigurationSetting setValue(String value) { tryParseValue(value); isValidFeatureFlagValue = true; super.setValue(value); return this; } /** * Sets the label of this configuration setting. {@link * set. * * @param label The label of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setLabel(String label) { super.setLabel(label); return this; } /** * Sets the content type. By default, the content type is null. * * @param contentType The content type of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setContentType(String contentType) { super.setContentType(contentType); return this; } /** * Sets the ETag for this configuration setting. * * @param etag The ETag for the configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setETag(String etag) { super.setETag(etag); return this; } /** * Sets the tags for this configuration setting. * * @param tags The tags to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. */ @Override public FeatureFlagConfigurationSetting setTags(Map<String, String> tags) { super.setTags(tags); return this; } /** * Get the feature ID of this configuration setting. * * @return the feature ID of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getFeatureId() { checkValid(); return featureId; } /** * Set the feature ID of this configuration setting. * * @param featureId the feature ID of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setFeatureId(String featureId) { checkValid(); this.featureId = featureId; super.setKey(KEY_PREFIX + featureId); return this; } /** * Get the boolean indicator to show if the setting is turn on or off. * * @return the boolean indicator to show if the setting is turn on or off. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public boolean isEnabled() { checkValid(); return this.isEnabled; } /** * Set the boolean indicator to show if the setting is turn on or off. * * @param isEnabled the boolean indicator to show if the setting is turn on or off. * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setEnabled(boolean isEnabled) { checkValid(); this.isEnabled = isEnabled; return this; } /** * Get the description of this configuration setting. * * @return the description of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDescription() { checkValid(); return description; } /** * Set the description of this configuration setting. * * @param description the description of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDescription(String description) { checkValid(); this.description = description; return this; } /** * Get the display name of this configuration setting. * * @return the display name of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public String getDisplayName() { checkValid(); return displayName; } /** * Set the display name of this configuration setting. * * @param displayName the display name of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setDisplayName(String displayName) { checkValid(); this.displayName = displayName; return this; } /** * Gets the feature flag filters of this configuration setting. * * @return the feature flag filters of this configuration setting. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public List<FeatureFlagFilter> getClientFilters() { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } return clientFilters; } /** * Sets the feature flag filters of this configuration setting. * * @param clientFilters the feature flag filters of this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting setClientFilters(List<FeatureFlagFilter> clientFilters) { checkValid(); this.clientFilters = clientFilters; return this; } /** * Add a feature flag filter to this configuration setting. * * @param clientFilter a feature flag filter to add to this configuration setting. * * @return The updated {@link FeatureFlagConfigurationSetting} object. * @throws IllegalArgumentException if the setting's {@code value} is an invalid JSON format. */ public FeatureFlagConfigurationSetting addClientFilter(FeatureFlagFilter clientFilter) { checkValid(); if (clientFilters == null) { clientFilters = new ArrayList<>(); } clientFilters.add(clientFilter); return this; } private void checkValid() { if (!isValidFeatureFlagValue) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The content of the " + super.getValue() + " property do not represent a valid feature flag configuration setting.")); } } private boolean tryWriteKnownProperty(String propertyName, Object propertyValue, JsonWriter writer, boolean includeOptionalWhenNull) throws IOException { switch (propertyName) { case ID: writer.writeStringField(ID, featureId); break; case DESCRIPTION: if (includeOptionalWhenNull || description != null) { writer.writeStringField(DESCRIPTION, description); } break; case DISPLAY_NAME: if (includeOptionalWhenNull || displayName != null) { writer.writeStringField(DISPLAY_NAME, displayName); } break; case ENABLED: writer.writeBooleanField(ENABLED, isEnabled); break; case CONDITIONS: tryWriteConditions(propertyValue, writer); break; default: return false; } return true; } private void tryWriteConditions(Object propertyValue, JsonWriter writer) throws IOException { writer.writeStartObject(CONDITIONS); if (propertyValue != null && propertyValue instanceof Conditions) { Conditions propertyValueClone = (Conditions) propertyValue; for (Map.Entry<String, Object> entry : propertyValueClone.getUnknownConditions().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); writer.writeUntypedField(key, value); } } writer.writeArrayField(CLIENT_FILTERS, this.clientFilters, (jsonWriter, filter) -> { jsonWriter.writeStartObject(); jsonWriter.writeStringField(NAME, filter.getName()); jsonWriter.writeMapField(PARAMETERS, filter.getParameters(), JsonWriter::writeUntyped); jsonWriter.writeEndObject(); }); writer.writeEndObject(); } private void tryParseValue(String value) { parsedProperties.clear(); try (JsonReader jsonReader = JsonProviders.createReader(value)) { jsonReader.readObject(reader -> { final Set<String> requiredPropertiesCopy = new LinkedHashSet<>(requiredJsonProperties); String featureIdCopy = this.featureId; String descriptionCopy = this.description; String displayNameCopy = this.displayName; boolean isEnabledCopy = this.isEnabled; List<FeatureFlagFilter> featureFlagFiltersCopy = this.clientFilters; while (reader.nextToken() != JsonToken.END_OBJECT) { final String fieldName = reader.getFieldName(); reader.nextToken(); if (ID.equals(fieldName)) { final String id = reader.getString(); featureIdCopy = id; parsedProperties.put(ID, id); } else if (DESCRIPTION.equals(fieldName)) { final String description = reader.getString(); descriptionCopy = description; parsedProperties.put(DESCRIPTION, description); } else if (DISPLAY_NAME.equals(fieldName)) { final String displayName = reader.getString(); displayNameCopy = displayName; parsedProperties.put(DISPLAY_NAME, displayName); } else if (ENABLED.equals(fieldName)) { final boolean isEnabled = reader.getBoolean(); isEnabledCopy = isEnabled; parsedProperties.put(ENABLED, isEnabled); } else if (CONDITIONS.equals(fieldName)) { final Conditions conditions = readConditions(reader); if (conditions != null) { List<FeatureFlagFilter> featureFlagFilters = conditions.getFeatureFlagFilters(); featureFlagFiltersCopy = featureFlagFilters; parsedProperties.put(CONDITIONS, conditions); } } else { parsedProperties.put(fieldName, reader.readUntyped()); } requiredPropertiesCopy.remove(fieldName); } this.featureId = featureIdCopy; this.description = descriptionCopy; this.displayName = displayNameCopy; this.isEnabled = isEnabledCopy; this.clientFilters = featureFlagFiltersCopy; return requiredPropertiesCopy.isEmpty(); }); } catch (IOException e) { isValidFeatureFlagValue = false; throw LOGGER.logExceptionAsError(new IllegalArgumentException(e)); } } }
On local sdk-developer setup, it is expected to use RECORD mode if running tests against real service is desired (Note: the AMQP traffic never gets recorded to files). For local runs, the DefaultAzureCredential is enabled per recommendation. But I kept the connection string as an option for sdk-dev inner loop . If connection string is not set, then DefaultAzureCredential is attempted. If/when we drop connection string local sdk-dev experience, it's simply about removing the above if condition. This is a follow up item not scoped to this pr.
protected ServiceBusClientBuilder getAuthenticatedBuilder() { final TestMode mode = super.getTestMode(); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder(); if (mode == TestMode.LIVE) { final String fullyQualifiedDomainName = TestUtils.getLiveFullyQualifiedDomainName(); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = TestUtils.getPipelineCredential(credentialCached); return builder.credential(fullyQualifiedDomainName, credential); } else if (mode == TestMode.RECORD) { final String connectionString = TestUtils.getConnectionString(false); if (CoreUtils.isNullOrEmpty(connectionString)) { final String fullyQualifiedDomainName = TestUtils.getLiveFullyQualifiedDomainName(); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); return builder.credential(fullyQualifiedDomainName, credential); } else { return builder.connectionString(connectionString); } } else { throw new TestAbortedException("Integration tests are not enabled in playback mode."); } }
return builder.connectionString(connectionString);
protected ServiceBusClientBuilder getAuthenticatedBuilder() { final TestMode mode = super.getTestMode(); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder(); if (mode == TestMode.LIVE) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(false); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = TestUtils.getPipelineCredential(credentialCached); return builder.credential(fullyQualifiedDomainName, credential); } else if (mode == TestMode.RECORD) { final String connectionString = TestUtils.getConnectionString(false); if (CoreUtils.isNullOrEmpty(connectionString)) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(false); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); return builder.credential(fullyQualifiedDomainName, credential); } else { return builder.connectionString(connectionString); } } else { assumeTrue(false, "Integration tests are not enabled in playback mode."); return null; } }
class IntegrationTestBase extends TestBase { protected static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(30); protected static final Duration TIMEOUT = Duration.ofSeconds(60); protected static final AmqpRetryOptions RETRY_OPTIONS = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(3)); protected final ClientLogger logger; protected ClientOptions optionsWithTracing; private static final String PROXY_AUTHENTICATION_TYPE = "PROXY_AUTHENTICATION_TYPE"; private static final Configuration GLOBAL_CONFIGURATION = TestUtils.getGlobalConfiguration(); private List<AutoCloseable> toClose = new ArrayList<>(); private String testName; private final Scheduler scheduler = Schedulers.parallel(); private final AtomicReference<TokenCredential> credentialCached = new AtomicReference<>(); protected static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8); protected String sessionId; ServiceBusClientBuilder sharedBuilder; protected IntegrationTestBase(ClientLogger logger) { this.logger = logger; } @BeforeEach @Override public void setupTest(TestContextManager testContextManager) { this.testContextManager = testContextManager; testName = testContextManager.getTrackerTestName(); logger.info("========= SET-UP [{}] =========", testName); assertRunnable(); toClose = new ArrayList<>(); optionsWithTracing = new ClientOptions().setTracingOptions(new LoggingTracerProvider.LoggingTracingOptions()); beforeTest(); } @AfterEach @Override public void teardownTest() { logger.info("========= TEARDOWN [{}] =========", testName); afterTest(); logger.info("Disposing of subscriptions, consumers and clients."); dispose(); } /** * Gets the name of the queue. * * @param index Index of the queue. * * @return Name of the queue. */ public String getQueueName(int index) { return getEntityName(getQueueBaseName(), index); } public String getSessionQueueName(int index) { return getEntityName(getSessionQueueBaseName(), index); } /** * Gets the name of the topic. * * @return Name of the topic. */ public String getTopicName(int index) { return getEntityName(TestUtils.getTopicBaseName(), index); } /** * Gets the configured ProxyConfiguration from environment variables. */ public ProxyOptions getProxyConfiguration() { final String address = GLOBAL_CONFIGURATION.get(Configuration.PROPERTY_HTTP_PROXY); if (address == null) { return null; } final String[] host = address.split(":"); if (host.length < 2) { logger.warning("Environment variable '{}' cannot be parsed into a proxy. Value: {}", Configuration.PROPERTY_HTTP_PROXY, address); return null; } final String hostname = host[0]; final int port = Integer.parseInt(host[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port)); final String username = GLOBAL_CONFIGURATION.get(PROXY_USERNAME); if (username == null) { logger.info("Environment variable '{}' is not set. No authentication used."); return new ProxyOptions(ProxyAuthenticationType.NONE, proxy, null, null); } final String password = GLOBAL_CONFIGURATION.get(PROXY_PASSWORD); final String authentication = GLOBAL_CONFIGURATION.get(PROXY_AUTHENTICATION_TYPE); final ProxyAuthenticationType authenticationType = CoreUtils.isNullOrEmpty(authentication) ? ProxyAuthenticationType.NONE : ProxyAuthenticationType.valueOf(authentication); return new ProxyOptions(authenticationType, proxy, username, password); } /** * Creates a new instance of {@link ServiceBusClientBuilder} with authentication set up in {@link TestMode * {@link TestMode * * @return the builder with authentication set up. * @throws org.opentest4j.TestAbortedException if the test mode is {@link TestMode */ /** * Creates a new instance of {@link ServiceBusClientBuilder} with the default integration test settings. */ protected ServiceBusClientBuilder getBuilder() { return getAuthenticatedBuilder() .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) .clientOptions(optionsWithTracing) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler) .configuration(v1OrV2(true)); } protected ServiceBusClientBuilder getBuilder(boolean sharedConnection) { ServiceBusClientBuilder builder; if (sharedConnection && sharedBuilder == null) { sharedBuilder = getBuilder(); builder = sharedBuilder; } else if (sharedConnection) { builder = sharedBuilder; } else { builder = getBuilder(); } return builder; } protected ServiceBusSenderClientBuilder getSenderBuilder(MessagingEntityType entityType, int entityIndex, boolean isSessionAware, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = isSessionAware ? getSessionQueueName(entityIndex) : getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.sender() .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); assertNotNull(topicName, "'topicName' cannot be null."); return builder.sender().topicName(topicName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusReceiverClientBuilder getReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK).queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusSessionReceiverClientBuilder getSessionReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection, AmqpRetryOptions retryOptions) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getSessionQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSessionSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected static Stream<Arguments> messagingEntityProvider() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE), Arguments.of(MessagingEntityType.SUBSCRIPTION) ); } protected static Stream<Arguments> messagingEntityWithSessions() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, false), Arguments.of(MessagingEntityType.SUBSCRIPTION, false), Arguments.of(MessagingEntityType.QUEUE, true), Arguments.of(MessagingEntityType.SUBSCRIPTION, true) ); } protected static Stream<Arguments> receiveDeferredMessageBySequenceNumber() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.SUSPENDED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.SUSPENDED) ); } protected <T extends AutoCloseable> T toClose(T closeable) { toClose.add(closeable); return closeable; } protected Disposable toClose(Disposable closeable) { toClose.add(() -> closeable.dispose()); return closeable; } /** * Disposes of registered with {@code toClose} method resources. */ protected void dispose() { dispose(toClose.toArray(new AutoCloseable[0])); toClose.clear(); } /** * Disposes of any {@link Closeable} resources. * * @param closeables The closeables to dispose of. If a closeable is {@code null}, it is skipped. */ protected void dispose(AutoCloseable... closeables) { if (closeables == null || closeables.length == 0) { return; } final List<Mono<Void>> closeableMonos = new ArrayList<>(); for (final AutoCloseable closeable : closeables) { if (closeable == null) { continue; } if (closeable instanceof AsyncCloseable) { final Mono<Void> voidMono = ((AsyncCloseable) closeable).closeAsync(); closeableMonos.add(voidMono); voidMono.subscribe(); } try { closeable.close(); } catch (Exception error) { logger.error("[{}]: {} didn't close properly.", testName, closeable.getClass().getSimpleName(), error); } } Mono.when(closeableMonos).block(TIMEOUT); } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled, AmqpMessageBody amqpMessageBody) { final ServiceBusMessage message = new ServiceBusMessage(amqpMessageBody); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled) { final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected void logMessage(ServiceBusMessage message, String entity, String description) { logMessage(message.getMessageId(), -1, message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } protected void logMessage(ServiceBusReceivedMessage message, String entity, String description) { if (message == null) { logMessage(null, -1, entity, null, description); } else { logMessage(message.getMessageId(), message.getSequenceNumber(), message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } } private void logMessage(String id, long seqNo, Object positionId, String entity, String description) { logger.atInfo() .addKeyValue("test", testName) .addKeyValue("entity", entity) .addKeyValue("sequenceNo", seqNo) .addKeyValue("messageId", id) .addKeyValue("positionId", positionId) .log(description == null ? "logging messages" : description); } protected void logMessages(List<ServiceBusMessage> messages, String entity, String description) { messages.forEach(m -> logMessage(m.getMessageId(), -1, m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); } protected List<ServiceBusReceivedMessage> logReceivedMessages(IterableStream<ServiceBusReceivedMessage> messages, String entity, String description) { List<ServiceBusReceivedMessage> list = messages.stream().collect(Collectors.toList()); list.forEach(m -> logMessage(m.getMessageId(), m.getSequenceNumber(), m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); return list; } protected void assertMessageEquals(ServiceBusReceivedMessage message, String messageId, boolean isSessionEnabled) { assertNotNull(message, "'message' cannot be null."); assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertNotNull(message.getMessageId(), "'messageId' cannot be null."); if (isSessionEnabled) { assertNotNull(message.getSessionId(), "'sessionId' cannot be null."); } } protected final Configuration v1OrV2(boolean isV2) { final TestConfigurationSource configSource = new TestConfigurationSource(); if (isV2) { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "true"); } else { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "false"); } return new ConfigurationBuilder(configSource) .build(); } /** * Asserts that if the integration tests can be run. This method is expected to be called at the beginning of each * test run. * * @throws TestAbortedException if the integration tests cannot be run. */ protected void assertRunnable() { final TestMode mode = super.getTestMode(); if (mode == TestMode.PLAYBACK) { throw new TestAbortedException("Skipping integration tests in playback mode."); } if (mode == TestMode.RECORD) { if (!CoreUtils.isNullOrEmpty(TestUtils.getConnectionString(false))) { return; } if (!CoreUtils.isNullOrEmpty(TestUtils.getFullyQualifiedDomainName())) { return; } throw new TestAbortedException("Not running integration in record mode (missing authentication set up)."); } assert mode == TestMode.LIVE; } }
class IntegrationTestBase extends TestBase { protected static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(30); protected static final Duration TIMEOUT = Duration.ofSeconds(60); protected static final AmqpRetryOptions RETRY_OPTIONS = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(3)); protected final ClientLogger logger; protected ClientOptions optionsWithTracing; private static final String PROXY_AUTHENTICATION_TYPE = "PROXY_AUTHENTICATION_TYPE"; private static final Configuration GLOBAL_CONFIGURATION = TestUtils.getGlobalConfiguration(); private List<AutoCloseable> toClose = new ArrayList<>(); private String testName; private final Scheduler scheduler = Schedulers.parallel(); private final AtomicReference<TokenCredential> credentialCached = new AtomicReference<>(); protected static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8); protected String sessionId; ServiceBusClientBuilder sharedBuilder; protected IntegrationTestBase(ClientLogger logger) { this.logger = logger; } @BeforeEach @Override public void setupTest(TestContextManager testContextManager) { this.testContextManager = testContextManager; testName = testContextManager.getTrackerTestName(); logger.info("========= SET-UP [{}] =========", testName); assertRunnable(); toClose = new ArrayList<>(); optionsWithTracing = new ClientOptions().setTracingOptions(new LoggingTracerProvider.LoggingTracingOptions()); beforeTest(); } @AfterEach @Override public void teardownTest() { logger.info("========= TEARDOWN [{}] =========", testName); afterTest(); logger.info("Disposing of subscriptions, consumers and clients."); dispose(); } /** * Gets the name of the queue. * * @param index Index of the queue. * * @return Name of the queue. */ public String getQueueName(int index) { return getEntityName(getQueueBaseName(), index); } public String getSessionQueueName(int index) { return getEntityName(getSessionQueueBaseName(), index); } /** * Gets the name of the topic. * * @return Name of the topic. */ public String getTopicName(int index) { return getEntityName(TestUtils.getTopicBaseName(), index); } /** * Gets the configured ProxyConfiguration from environment variables. */ public ProxyOptions getProxyConfiguration() { final String address = GLOBAL_CONFIGURATION.get(Configuration.PROPERTY_HTTP_PROXY); if (address == null) { return null; } final String[] host = address.split(":"); if (host.length < 2) { logger.warning("Environment variable '{}' cannot be parsed into a proxy. Value: {}", Configuration.PROPERTY_HTTP_PROXY, address); return null; } final String hostname = host[0]; final int port = Integer.parseInt(host[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port)); final String username = GLOBAL_CONFIGURATION.get(PROXY_USERNAME); if (username == null) { logger.info("Environment variable '{}' is not set. No authentication used."); return new ProxyOptions(ProxyAuthenticationType.NONE, proxy, null, null); } final String password = GLOBAL_CONFIGURATION.get(PROXY_PASSWORD); final String authentication = GLOBAL_CONFIGURATION.get(PROXY_AUTHENTICATION_TYPE); final ProxyAuthenticationType authenticationType = CoreUtils.isNullOrEmpty(authentication) ? ProxyAuthenticationType.NONE : ProxyAuthenticationType.valueOf(authentication); return new ProxyOptions(authenticationType, proxy, username, password); } /** * Creates a new instance of {@link ServiceBusClientBuilder} with authentication set up in {@link TestMode * {@link TestMode * * @return the builder with authentication set up. * @throws org.opentest4j.TestAbortedException if the test mode is {@link TestMode */ /** * Creates a new instance of {@link ServiceBusClientBuilder} with the default integration test settings. */ protected ServiceBusClientBuilder getBuilder() { return getAuthenticatedBuilder() .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) .clientOptions(optionsWithTracing) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler) .configuration(v1OrV2(true)); } protected ServiceBusClientBuilder getBuilder(boolean sharedConnection) { ServiceBusClientBuilder builder; if (sharedConnection && sharedBuilder == null) { sharedBuilder = getBuilder(); builder = sharedBuilder; } else if (sharedConnection) { builder = sharedBuilder; } else { builder = getBuilder(); } return builder; } protected ServiceBusSenderClientBuilder getSenderBuilder(MessagingEntityType entityType, int entityIndex, boolean isSessionAware, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = isSessionAware ? getSessionQueueName(entityIndex) : getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.sender() .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); assertNotNull(topicName, "'topicName' cannot be null."); return builder.sender().topicName(topicName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusReceiverClientBuilder getReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK).queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusSessionReceiverClientBuilder getSessionReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection, AmqpRetryOptions retryOptions) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getSessionQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSessionSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected static Stream<Arguments> messagingEntityProvider() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE), Arguments.of(MessagingEntityType.SUBSCRIPTION) ); } protected static Stream<Arguments> messagingEntityWithSessions() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, false), Arguments.of(MessagingEntityType.SUBSCRIPTION, false), Arguments.of(MessagingEntityType.QUEUE, true), Arguments.of(MessagingEntityType.SUBSCRIPTION, true) ); } protected static Stream<Arguments> receiveDeferredMessageBySequenceNumber() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.SUSPENDED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.SUSPENDED) ); } protected <T extends AutoCloseable> T toClose(T closeable) { toClose.add(closeable); return closeable; } protected Disposable toClose(Disposable closeable) { toClose.add(() -> closeable.dispose()); return closeable; } /** * Disposes of registered with {@code toClose} method resources. */ protected void dispose() { dispose(toClose.toArray(new AutoCloseable[0])); toClose.clear(); } /** * Disposes of any {@link Closeable} resources. * * @param closeables The closeables to dispose of. If a closeable is {@code null}, it is skipped. */ protected void dispose(AutoCloseable... closeables) { if (closeables == null || closeables.length == 0) { return; } final List<Mono<Void>> closeableMonos = new ArrayList<>(); for (final AutoCloseable closeable : closeables) { if (closeable == null) { continue; } if (closeable instanceof AsyncCloseable) { final Mono<Void> voidMono = ((AsyncCloseable) closeable).closeAsync(); closeableMonos.add(voidMono); voidMono.subscribe(); } try { closeable.close(); } catch (Exception error) { logger.error("[{}]: {} didn't close properly.", testName, closeable.getClass().getSimpleName(), error); } } Mono.when(closeableMonos).block(TIMEOUT); } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled, AmqpMessageBody amqpMessageBody) { final ServiceBusMessage message = new ServiceBusMessage(amqpMessageBody); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled) { final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected void logMessage(ServiceBusMessage message, String entity, String description) { logMessage(message.getMessageId(), -1, message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } protected void logMessage(ServiceBusReceivedMessage message, String entity, String description) { if (message == null) { logMessage(null, -1, entity, null, description); } else { logMessage(message.getMessageId(), message.getSequenceNumber(), message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } } private void logMessage(String id, long seqNo, Object positionId, String entity, String description) { logger.atInfo() .addKeyValue("test", testName) .addKeyValue("entity", entity) .addKeyValue("sequenceNo", seqNo) .addKeyValue("messageId", id) .addKeyValue("positionId", positionId) .log(description == null ? "logging messages" : description); } protected void logMessages(List<ServiceBusMessage> messages, String entity, String description) { messages.forEach(m -> logMessage(m.getMessageId(), -1, m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); } protected List<ServiceBusReceivedMessage> logReceivedMessages(IterableStream<ServiceBusReceivedMessage> messages, String entity, String description) { List<ServiceBusReceivedMessage> list = messages.stream().collect(Collectors.toList()); list.forEach(m -> logMessage(m.getMessageId(), m.getSequenceNumber(), m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); return list; } protected void assertMessageEquals(ServiceBusReceivedMessage message, String messageId, boolean isSessionEnabled) { assertNotNull(message, "'message' cannot be null."); assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertNotNull(message.getMessageId(), "'messageId' cannot be null."); if (isSessionEnabled) { assertNotNull(message.getSessionId(), "'sessionId' cannot be null."); } } protected final Configuration v1OrV2(boolean isV2) { final TestConfigurationSource configSource = new TestConfigurationSource(); if (isV2) { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "true"); } else { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "false"); } return new ConfigurationBuilder(configSource) .build(); } /** * Asserts that if the integration tests can be run. This method is expected to be called at the beginning of each * test run. * * @throws org.opentest4j.TestAbortedException if the integration tests cannot be run. */ protected void assertRunnable() { final TestMode mode = super.getTestMode(); if (mode == TestMode.PLAYBACK) { assumeTrue(false, "Skipping integration tests in playback mode."); return; } if (mode == TestMode.RECORD) { if (!CoreUtils.isNullOrEmpty(TestUtils.getConnectionString(false))) { return; } if (!CoreUtils.isNullOrEmpty(TestUtils.getFullyQualifiedDomainName(false))) { return; } assumeTrue(false, "Not running integration in record mode (missing authentication set up)."); return; } assert mode == TestMode.LIVE; } }
Here following the recommended pattern of using pipeline credentials when running in LIVE mode,
protected ServiceBusClientBuilder getAuthenticatedBuilder() { final TestMode mode = super.getTestMode(); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder(); if (mode == TestMode.LIVE) { final String fullyQualifiedDomainName = TestUtils.getLiveFullyQualifiedDomainName(); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = TestUtils.getPipelineCredential(credentialCached); return builder.credential(fullyQualifiedDomainName, credential); } else if (mode == TestMode.RECORD) { final String connectionString = TestUtils.getConnectionString(false); if (CoreUtils.isNullOrEmpty(connectionString)) { final String fullyQualifiedDomainName = TestUtils.getLiveFullyQualifiedDomainName(); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); return builder.credential(fullyQualifiedDomainName, credential); } else { return builder.connectionString(connectionString); } } else { throw new TestAbortedException("Integration tests are not enabled in playback mode."); } }
return builder.credential(fullyQualifiedDomainName, credential);
protected ServiceBusClientBuilder getAuthenticatedBuilder() { final TestMode mode = super.getTestMode(); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder(); if (mode == TestMode.LIVE) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(false); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = TestUtils.getPipelineCredential(credentialCached); return builder.credential(fullyQualifiedDomainName, credential); } else if (mode == TestMode.RECORD) { final String connectionString = TestUtils.getConnectionString(false); if (CoreUtils.isNullOrEmpty(connectionString)) { final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(false); assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "FullyQualifiedDomainName is not set."); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); return builder.credential(fullyQualifiedDomainName, credential); } else { return builder.connectionString(connectionString); } } else { assumeTrue(false, "Integration tests are not enabled in playback mode."); return null; } }
class IntegrationTestBase extends TestBase { protected static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(30); protected static final Duration TIMEOUT = Duration.ofSeconds(60); protected static final AmqpRetryOptions RETRY_OPTIONS = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(3)); protected final ClientLogger logger; protected ClientOptions optionsWithTracing; private static final String PROXY_AUTHENTICATION_TYPE = "PROXY_AUTHENTICATION_TYPE"; private static final Configuration GLOBAL_CONFIGURATION = TestUtils.getGlobalConfiguration(); private List<AutoCloseable> toClose = new ArrayList<>(); private String testName; private final Scheduler scheduler = Schedulers.parallel(); private final AtomicReference<TokenCredential> credentialCached = new AtomicReference<>(); protected static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8); protected String sessionId; ServiceBusClientBuilder sharedBuilder; protected IntegrationTestBase(ClientLogger logger) { this.logger = logger; } @BeforeEach @Override public void setupTest(TestContextManager testContextManager) { this.testContextManager = testContextManager; testName = testContextManager.getTrackerTestName(); logger.info("========= SET-UP [{}] =========", testName); assertRunnable(); toClose = new ArrayList<>(); optionsWithTracing = new ClientOptions().setTracingOptions(new LoggingTracerProvider.LoggingTracingOptions()); beforeTest(); } @AfterEach @Override public void teardownTest() { logger.info("========= TEARDOWN [{}] =========", testName); afterTest(); logger.info("Disposing of subscriptions, consumers and clients."); dispose(); } /** * Gets the name of the queue. * * @param index Index of the queue. * * @return Name of the queue. */ public String getQueueName(int index) { return getEntityName(getQueueBaseName(), index); } public String getSessionQueueName(int index) { return getEntityName(getSessionQueueBaseName(), index); } /** * Gets the name of the topic. * * @return Name of the topic. */ public String getTopicName(int index) { return getEntityName(TestUtils.getTopicBaseName(), index); } /** * Gets the configured ProxyConfiguration from environment variables. */ public ProxyOptions getProxyConfiguration() { final String address = GLOBAL_CONFIGURATION.get(Configuration.PROPERTY_HTTP_PROXY); if (address == null) { return null; } final String[] host = address.split(":"); if (host.length < 2) { logger.warning("Environment variable '{}' cannot be parsed into a proxy. Value: {}", Configuration.PROPERTY_HTTP_PROXY, address); return null; } final String hostname = host[0]; final int port = Integer.parseInt(host[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port)); final String username = GLOBAL_CONFIGURATION.get(PROXY_USERNAME); if (username == null) { logger.info("Environment variable '{}' is not set. No authentication used."); return new ProxyOptions(ProxyAuthenticationType.NONE, proxy, null, null); } final String password = GLOBAL_CONFIGURATION.get(PROXY_PASSWORD); final String authentication = GLOBAL_CONFIGURATION.get(PROXY_AUTHENTICATION_TYPE); final ProxyAuthenticationType authenticationType = CoreUtils.isNullOrEmpty(authentication) ? ProxyAuthenticationType.NONE : ProxyAuthenticationType.valueOf(authentication); return new ProxyOptions(authenticationType, proxy, username, password); } /** * Creates a new instance of {@link ServiceBusClientBuilder} with authentication set up in {@link TestMode * {@link TestMode * * @return the builder with authentication set up. * @throws org.opentest4j.TestAbortedException if the test mode is {@link TestMode */ /** * Creates a new instance of {@link ServiceBusClientBuilder} with the default integration test settings. */ protected ServiceBusClientBuilder getBuilder() { return getAuthenticatedBuilder() .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) .clientOptions(optionsWithTracing) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler) .configuration(v1OrV2(true)); } protected ServiceBusClientBuilder getBuilder(boolean sharedConnection) { ServiceBusClientBuilder builder; if (sharedConnection && sharedBuilder == null) { sharedBuilder = getBuilder(); builder = sharedBuilder; } else if (sharedConnection) { builder = sharedBuilder; } else { builder = getBuilder(); } return builder; } protected ServiceBusSenderClientBuilder getSenderBuilder(MessagingEntityType entityType, int entityIndex, boolean isSessionAware, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = isSessionAware ? getSessionQueueName(entityIndex) : getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.sender() .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); assertNotNull(topicName, "'topicName' cannot be null."); return builder.sender().topicName(topicName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusReceiverClientBuilder getReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK).queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusSessionReceiverClientBuilder getSessionReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection, AmqpRetryOptions retryOptions) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getSessionQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSessionSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected static Stream<Arguments> messagingEntityProvider() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE), Arguments.of(MessagingEntityType.SUBSCRIPTION) ); } protected static Stream<Arguments> messagingEntityWithSessions() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, false), Arguments.of(MessagingEntityType.SUBSCRIPTION, false), Arguments.of(MessagingEntityType.QUEUE, true), Arguments.of(MessagingEntityType.SUBSCRIPTION, true) ); } protected static Stream<Arguments> receiveDeferredMessageBySequenceNumber() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.SUSPENDED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.SUSPENDED) ); } protected <T extends AutoCloseable> T toClose(T closeable) { toClose.add(closeable); return closeable; } protected Disposable toClose(Disposable closeable) { toClose.add(() -> closeable.dispose()); return closeable; } /** * Disposes of registered with {@code toClose} method resources. */ protected void dispose() { dispose(toClose.toArray(new AutoCloseable[0])); toClose.clear(); } /** * Disposes of any {@link Closeable} resources. * * @param closeables The closeables to dispose of. If a closeable is {@code null}, it is skipped. */ protected void dispose(AutoCloseable... closeables) { if (closeables == null || closeables.length == 0) { return; } final List<Mono<Void>> closeableMonos = new ArrayList<>(); for (final AutoCloseable closeable : closeables) { if (closeable == null) { continue; } if (closeable instanceof AsyncCloseable) { final Mono<Void> voidMono = ((AsyncCloseable) closeable).closeAsync(); closeableMonos.add(voidMono); voidMono.subscribe(); } try { closeable.close(); } catch (Exception error) { logger.error("[{}]: {} didn't close properly.", testName, closeable.getClass().getSimpleName(), error); } } Mono.when(closeableMonos).block(TIMEOUT); } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled, AmqpMessageBody amqpMessageBody) { final ServiceBusMessage message = new ServiceBusMessage(amqpMessageBody); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled) { final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected void logMessage(ServiceBusMessage message, String entity, String description) { logMessage(message.getMessageId(), -1, message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } protected void logMessage(ServiceBusReceivedMessage message, String entity, String description) { if (message == null) { logMessage(null, -1, entity, null, description); } else { logMessage(message.getMessageId(), message.getSequenceNumber(), message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } } private void logMessage(String id, long seqNo, Object positionId, String entity, String description) { logger.atInfo() .addKeyValue("test", testName) .addKeyValue("entity", entity) .addKeyValue("sequenceNo", seqNo) .addKeyValue("messageId", id) .addKeyValue("positionId", positionId) .log(description == null ? "logging messages" : description); } protected void logMessages(List<ServiceBusMessage> messages, String entity, String description) { messages.forEach(m -> logMessage(m.getMessageId(), -1, m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); } protected List<ServiceBusReceivedMessage> logReceivedMessages(IterableStream<ServiceBusReceivedMessage> messages, String entity, String description) { List<ServiceBusReceivedMessage> list = messages.stream().collect(Collectors.toList()); list.forEach(m -> logMessage(m.getMessageId(), m.getSequenceNumber(), m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); return list; } protected void assertMessageEquals(ServiceBusReceivedMessage message, String messageId, boolean isSessionEnabled) { assertNotNull(message, "'message' cannot be null."); assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertNotNull(message.getMessageId(), "'messageId' cannot be null."); if (isSessionEnabled) { assertNotNull(message.getSessionId(), "'sessionId' cannot be null."); } } protected final Configuration v1OrV2(boolean isV2) { final TestConfigurationSource configSource = new TestConfigurationSource(); if (isV2) { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "true"); } else { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "false"); } return new ConfigurationBuilder(configSource) .build(); } /** * Asserts that if the integration tests can be run. This method is expected to be called at the beginning of each * test run. * * @throws TestAbortedException if the integration tests cannot be run. */ protected void assertRunnable() { final TestMode mode = super.getTestMode(); if (mode == TestMode.PLAYBACK) { throw new TestAbortedException("Skipping integration tests in playback mode."); } if (mode == TestMode.RECORD) { if (!CoreUtils.isNullOrEmpty(TestUtils.getConnectionString(false))) { return; } if (!CoreUtils.isNullOrEmpty(TestUtils.getFullyQualifiedDomainName())) { return; } throw new TestAbortedException("Not running integration in record mode (missing authentication set up)."); } assert mode == TestMode.LIVE; } }
class IntegrationTestBase extends TestBase { protected static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(30); protected static final Duration TIMEOUT = Duration.ofSeconds(60); protected static final AmqpRetryOptions RETRY_OPTIONS = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(3)); protected final ClientLogger logger; protected ClientOptions optionsWithTracing; private static final String PROXY_AUTHENTICATION_TYPE = "PROXY_AUTHENTICATION_TYPE"; private static final Configuration GLOBAL_CONFIGURATION = TestUtils.getGlobalConfiguration(); private List<AutoCloseable> toClose = new ArrayList<>(); private String testName; private final Scheduler scheduler = Schedulers.parallel(); private final AtomicReference<TokenCredential> credentialCached = new AtomicReference<>(); protected static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8); protected String sessionId; ServiceBusClientBuilder sharedBuilder; protected IntegrationTestBase(ClientLogger logger) { this.logger = logger; } @BeforeEach @Override public void setupTest(TestContextManager testContextManager) { this.testContextManager = testContextManager; testName = testContextManager.getTrackerTestName(); logger.info("========= SET-UP [{}] =========", testName); assertRunnable(); toClose = new ArrayList<>(); optionsWithTracing = new ClientOptions().setTracingOptions(new LoggingTracerProvider.LoggingTracingOptions()); beforeTest(); } @AfterEach @Override public void teardownTest() { logger.info("========= TEARDOWN [{}] =========", testName); afterTest(); logger.info("Disposing of subscriptions, consumers and clients."); dispose(); } /** * Gets the name of the queue. * * @param index Index of the queue. * * @return Name of the queue. */ public String getQueueName(int index) { return getEntityName(getQueueBaseName(), index); } public String getSessionQueueName(int index) { return getEntityName(getSessionQueueBaseName(), index); } /** * Gets the name of the topic. * * @return Name of the topic. */ public String getTopicName(int index) { return getEntityName(TestUtils.getTopicBaseName(), index); } /** * Gets the configured ProxyConfiguration from environment variables. */ public ProxyOptions getProxyConfiguration() { final String address = GLOBAL_CONFIGURATION.get(Configuration.PROPERTY_HTTP_PROXY); if (address == null) { return null; } final String[] host = address.split(":"); if (host.length < 2) { logger.warning("Environment variable '{}' cannot be parsed into a proxy. Value: {}", Configuration.PROPERTY_HTTP_PROXY, address); return null; } final String hostname = host[0]; final int port = Integer.parseInt(host[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port)); final String username = GLOBAL_CONFIGURATION.get(PROXY_USERNAME); if (username == null) { logger.info("Environment variable '{}' is not set. No authentication used."); return new ProxyOptions(ProxyAuthenticationType.NONE, proxy, null, null); } final String password = GLOBAL_CONFIGURATION.get(PROXY_PASSWORD); final String authentication = GLOBAL_CONFIGURATION.get(PROXY_AUTHENTICATION_TYPE); final ProxyAuthenticationType authenticationType = CoreUtils.isNullOrEmpty(authentication) ? ProxyAuthenticationType.NONE : ProxyAuthenticationType.valueOf(authentication); return new ProxyOptions(authenticationType, proxy, username, password); } /** * Creates a new instance of {@link ServiceBusClientBuilder} with authentication set up in {@link TestMode * {@link TestMode * * @return the builder with authentication set up. * @throws org.opentest4j.TestAbortedException if the test mode is {@link TestMode */ /** * Creates a new instance of {@link ServiceBusClientBuilder} with the default integration test settings. */ protected ServiceBusClientBuilder getBuilder() { return getAuthenticatedBuilder() .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) .clientOptions(optionsWithTracing) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler) .configuration(v1OrV2(true)); } protected ServiceBusClientBuilder getBuilder(boolean sharedConnection) { ServiceBusClientBuilder builder; if (sharedConnection && sharedBuilder == null) { sharedBuilder = getBuilder(); builder = sharedBuilder; } else if (sharedConnection) { builder = sharedBuilder; } else { builder = getBuilder(); } return builder; } protected ServiceBusSenderClientBuilder getSenderBuilder(MessagingEntityType entityType, int entityIndex, boolean isSessionAware, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = isSessionAware ? getSessionQueueName(entityIndex) : getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.sender() .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); assertNotNull(topicName, "'topicName' cannot be null."); return builder.sender().topicName(topicName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusReceiverClientBuilder getReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK).queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder.receiver().receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected ServiceBusSessionReceiverClientBuilder getSessionReceiverBuilder(MessagingEntityType entityType, int entityIndex, boolean sharedConnection, AmqpRetryOptions retryOptions) { ServiceBusClientBuilder builder = getBuilder(sharedConnection); switch (entityType) { case QUEUE: final String queueName = getSessionQueueName(entityIndex); assertNotNull(queueName, "'queueName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName); case SUBSCRIPTION: final String topicName = getTopicName(entityIndex); final String subscriptionName = getSessionSubscriptionBaseName(); assertNotNull(topicName, "'topicName' cannot be null."); assertNotNull(subscriptionName, "'subscriptionName' cannot be null."); return builder .retryOptions(retryOptions) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName(topicName).subscriptionName(subscriptionName); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType)); } } protected static Stream<Arguments> messagingEntityProvider() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE), Arguments.of(MessagingEntityType.SUBSCRIPTION) ); } protected static Stream<Arguments> messagingEntityWithSessions() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, false), Arguments.of(MessagingEntityType.SUBSCRIPTION, false), Arguments.of(MessagingEntityType.QUEUE, true), Arguments.of(MessagingEntityType.SUBSCRIPTION, true) ); } protected static Stream<Arguments> receiveDeferredMessageBySequenceNumber() { return Stream.of( Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.QUEUE, DispositionStatus.SUSPENDED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.ABANDONED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.COMPLETED), Arguments.of(MessagingEntityType.SUBSCRIPTION, DispositionStatus.SUSPENDED) ); } protected <T extends AutoCloseable> T toClose(T closeable) { toClose.add(closeable); return closeable; } protected Disposable toClose(Disposable closeable) { toClose.add(() -> closeable.dispose()); return closeable; } /** * Disposes of registered with {@code toClose} method resources. */ protected void dispose() { dispose(toClose.toArray(new AutoCloseable[0])); toClose.clear(); } /** * Disposes of any {@link Closeable} resources. * * @param closeables The closeables to dispose of. If a closeable is {@code null}, it is skipped. */ protected void dispose(AutoCloseable... closeables) { if (closeables == null || closeables.length == 0) { return; } final List<Mono<Void>> closeableMonos = new ArrayList<>(); for (final AutoCloseable closeable : closeables) { if (closeable == null) { continue; } if (closeable instanceof AsyncCloseable) { final Mono<Void> voidMono = ((AsyncCloseable) closeable).closeAsync(); closeableMonos.add(voidMono); voidMono.subscribe(); } try { closeable.close(); } catch (Exception error) { logger.error("[{}]: {} didn't close properly.", testName, closeable.getClass().getSimpleName(), error); } } Mono.when(closeableMonos).block(TIMEOUT); } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled, AmqpMessageBody amqpMessageBody) { final ServiceBusMessage message = new ServiceBusMessage(amqpMessageBody); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled) { final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); message.setMessageId(messageId); return isSessionEnabled ? message.setSessionId(sessionId) : message; } protected void logMessage(ServiceBusMessage message, String entity, String description) { logMessage(message.getMessageId(), -1, message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } protected void logMessage(ServiceBusReceivedMessage message, String entity, String description) { if (message == null) { logMessage(null, -1, entity, null, description); } else { logMessage(message.getMessageId(), message.getSequenceNumber(), message.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description); } } private void logMessage(String id, long seqNo, Object positionId, String entity, String description) { logger.atInfo() .addKeyValue("test", testName) .addKeyValue("entity", entity) .addKeyValue("sequenceNo", seqNo) .addKeyValue("messageId", id) .addKeyValue("positionId", positionId) .log(description == null ? "logging messages" : description); } protected void logMessages(List<ServiceBusMessage> messages, String entity, String description) { messages.forEach(m -> logMessage(m.getMessageId(), -1, m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); } protected List<ServiceBusReceivedMessage> logReceivedMessages(IterableStream<ServiceBusReceivedMessage> messages, String entity, String description) { List<ServiceBusReceivedMessage> list = messages.stream().collect(Collectors.toList()); list.forEach(m -> logMessage(m.getMessageId(), m.getSequenceNumber(), m.getApplicationProperties().get(MESSAGE_POSITION_ID), entity, description)); return list; } protected void assertMessageEquals(ServiceBusReceivedMessage message, String messageId, boolean isSessionEnabled) { assertNotNull(message, "'message' cannot be null."); assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes()); assertNotNull(message.getMessageId(), "'messageId' cannot be null."); if (isSessionEnabled) { assertNotNull(message.getSessionId(), "'sessionId' cannot be null."); } } protected final Configuration v1OrV2(boolean isV2) { final TestConfigurationSource configSource = new TestConfigurationSource(); if (isV2) { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "true"); } else { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "false"); } return new ConfigurationBuilder(configSource) .build(); } /** * Asserts that if the integration tests can be run. This method is expected to be called at the beginning of each * test run. * * @throws org.opentest4j.TestAbortedException if the integration tests cannot be run. */ protected void assertRunnable() { final TestMode mode = super.getTestMode(); if (mode == TestMode.PLAYBACK) { assumeTrue(false, "Skipping integration tests in playback mode."); return; } if (mode == TestMode.RECORD) { if (!CoreUtils.isNullOrEmpty(TestUtils.getConnectionString(false))) { return; } if (!CoreUtils.isNullOrEmpty(TestUtils.getFullyQualifiedDomainName(false))) { return; } assumeTrue(false, "Not running integration in record mode (missing authentication set up)."); return; } assert mode == TestMode.LIVE; } }
(just to be safe) ```suggestion } catch (Throwable t) { logger.error("QuickPulseDataSender failed to send a request", t); ```
public void run() { while (true) { HttpRequest post; try { post = sendQueue.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("QuickPulseDataSender was interrupted while waiting for a request", e); return; } if (quickPulseHeaderInfo.getQuickPulseStatus() != QuickPulseStatus.QP_IS_ON) { logger.verbose("QuickPulseDataSender is not sending data because QP is " + quickPulseHeaderInfo.getQuickPulseStatus()); continue; } long sendTime = System.nanoTime(); try (HttpResponse response = httpPipeline.send(post).block()) { if (response == null) { throw new AssertionError("http response mono returned empty"); } if (networkHelper.isSuccess(response)) { QuickPulseHeaderInfo quickPulseHeaderInfo = networkHelper.getQuickPulseHeaderInfo(response); switch (quickPulseHeaderInfo.getQuickPulseStatus()) { case QP_IS_OFF: case QP_IS_ON: lastValidTransmission = sendTime; this.quickPulseHeaderInfo = quickPulseHeaderInfo; break; case ERROR: onPostError(sendTime); break; } } } catch (Exception e) { logger.error("QuickPulseDataSender failed to send a request", e); } } }
logger.error("QuickPulseDataSender failed to send a request", e);
public void run() { while (true) { HttpRequest post; try { post = sendQueue.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("QuickPulseDataSender was interrupted while waiting for a request", e); return; } if (quickPulseHeaderInfo.getQuickPulseStatus() != QuickPulseStatus.QP_IS_ON) { logger.verbose("QuickPulseDataSender is not sending data because QP is " + quickPulseHeaderInfo.getQuickPulseStatus()); continue; } long sendTime = System.nanoTime(); try (HttpResponse response = httpPipeline.send(post).block()) { if (response == null) { throw new AssertionError("http response mono returned empty"); } if (networkHelper.isSuccess(response)) { QuickPulseHeaderInfo quickPulseHeaderInfo = networkHelper.getQuickPulseHeaderInfo(response); switch (quickPulseHeaderInfo.getQuickPulseStatus()) { case QP_IS_OFF: case QP_IS_ON: lastValidTransmission = sendTime; this.quickPulseHeaderInfo = quickPulseHeaderInfo; break; case ERROR: onPostError(sendTime); break; } } } catch (Throwable t) { logger.error("QuickPulseDataSender failed to send a request", t); } } }
class QuickPulseDataSender implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final HttpPipeline httpPipeline; private volatile QuickPulseHeaderInfo quickPulseHeaderInfo; private long lastValidTransmission = 0; private final ArrayBlockingQueue<HttpRequest> sendQueue; QuickPulseDataSender(HttpPipeline httpPipeline, ArrayBlockingQueue<HttpRequest> sendQueue) { this.httpPipeline = httpPipeline; this.sendQueue = sendQueue; } @Override void startSending() { quickPulseHeaderInfo = new QuickPulseHeaderInfo(QuickPulseStatus.QP_IS_ON); } QuickPulseHeaderInfo getQuickPulseHeaderInfo() { return quickPulseHeaderInfo; } private void onPostError(long sendTime) { double timeFromLastValidTransmission = (sendTime - lastValidTransmission) / 1000000000.0; if (timeFromLastValidTransmission >= 20.0) { quickPulseHeaderInfo = new QuickPulseHeaderInfo(QuickPulseStatus.ERROR); } } }
class QuickPulseDataSender implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); private final QuickPulseNetworkHelper networkHelper = new QuickPulseNetworkHelper(); private final HttpPipeline httpPipeline; private volatile QuickPulseHeaderInfo quickPulseHeaderInfo; private long lastValidTransmission = 0; private final ArrayBlockingQueue<HttpRequest> sendQueue; QuickPulseDataSender(HttpPipeline httpPipeline, ArrayBlockingQueue<HttpRequest> sendQueue) { this.httpPipeline = httpPipeline; this.sendQueue = sendQueue; } @Override void startSending() { quickPulseHeaderInfo = new QuickPulseHeaderInfo(QuickPulseStatus.QP_IS_ON); } QuickPulseHeaderInfo getQuickPulseHeaderInfo() { return quickPulseHeaderInfo; } private void onPostError(long sendTime) { double timeFromLastValidTransmission = (sendTime - lastValidTransmission) / 1000000000.0; if (timeFromLastValidTransmission >= 20.0) { quickPulseHeaderInfo = new QuickPulseHeaderInfo(QuickPulseStatus.ERROR); } } }
(this is my preference to be safe, even though prior code was different) ```suggestion } catch (Throwable t) { // Not supposed to happen logger.error("QuickPulseCoordinator failed", t); ```
public void run() { try { while (!stopped) { long sleepInMillis; if (pingMode) { sleepInMillis = ping(); } else { sleepInMillis = sendData(); } Thread.sleep(sleepInMillis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("QuickPulseCoordinator was interrupted", e); } catch (Exception exception) { logger.error("QuickPulseCoordinator failed", exception); } }
logger.error("QuickPulseCoordinator failed", exception);
public void run() { try { while (!stopped) { long sleepInMillis; if (pingMode) { sleepInMillis = ping(); } else { sleepInMillis = sendData(); } Thread.sleep(sleepInMillis); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("QuickPulseCoordinator was interrupted", e); } catch (Throwable t) { logger.error("QuickPulseCoordinator failed", t); } }
class QuickPulseCoordinator implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); @Nullable private String qpsServiceRedirectedEndpoint; private long qpsServicePollingIntervalHintMillis; private volatile boolean stopped = false; private volatile boolean pingMode = true; private final QuickPulseDataCollector collector; private final QuickPulsePingSender pingSender; private final QuickPulseDataFetcher dataFetcher; private final QuickPulseDataSender dataSender; private final long waitBetweenPingsInMillis; private final long waitBetweenPostsInMillis; private final long waitOnErrorInMillis; QuickPulseCoordinator(QuickPulseCoordinatorInitData initData) { dataSender = initData.dataSender; pingSender = initData.pingSender; dataFetcher = initData.dataFetcher; collector = initData.collector; waitBetweenPingsInMillis = initData.waitBetweenPingsInMillis; waitBetweenPostsInMillis = initData.waitBetweenPostsInMillis; waitOnErrorInMillis = initData.waitOnErrorInMillis; qpsServiceRedirectedEndpoint = null; qpsServicePollingIntervalHintMillis = -1; } @Override @SuppressWarnings("try") private long sendData() { dataFetcher.prepareQuickPulseDataForSend(qpsServiceRedirectedEndpoint); QuickPulseHeaderInfo currentQuickPulseHeaderInfo = dataSender.getQuickPulseHeaderInfo(); this.handleReceivedHeaders(currentQuickPulseHeaderInfo); collector.setQuickPulseStatus(currentQuickPulseHeaderInfo.getQuickPulseStatus()); switch (currentQuickPulseHeaderInfo.getQuickPulseStatus()) { case ERROR: pingMode = true; return waitOnErrorInMillis; case QP_IS_OFF: pingMode = true; return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; case QP_IS_ON: return waitBetweenPostsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Critical error while sending QP data: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } @SuppressWarnings("try") private long ping() { QuickPulseHeaderInfo pingResult = pingSender.ping(qpsServiceRedirectedEndpoint); this.handleReceivedHeaders(pingResult); collector.setQuickPulseStatus(pingResult.getQuickPulseStatus()); switch (pingResult.getQuickPulseStatus()) { case ERROR: return waitOnErrorInMillis; case QP_IS_ON: pingMode = false; dataSender.startSending(); return waitBetweenPostsInMillis; case QP_IS_OFF: return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_PING_ERROR.makeActive()) { logger.error("Critical error while ping QP: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } private void handleReceivedHeaders(QuickPulseHeaderInfo currentQuickPulseHeaderInfo) { String redirectLink = currentQuickPulseHeaderInfo.getQpsServiceEndpointRedirect(); if (!Strings.isNullOrEmpty(redirectLink)) { qpsServiceRedirectedEndpoint = redirectLink; } long newPollingInterval = currentQuickPulseHeaderInfo.getQpsServicePollingInterval(); if (newPollingInterval > 0) { qpsServicePollingIntervalHintMillis = newPollingInterval; } } void stop() { stopped = true; } }
class QuickPulseCoordinator implements Runnable { private static final ClientLogger logger = new ClientLogger(QuickPulseCoordinator.class); @Nullable private String qpsServiceRedirectedEndpoint; private long qpsServicePollingIntervalHintMillis; private volatile boolean stopped = false; private volatile boolean pingMode = true; private final QuickPulseDataCollector collector; private final QuickPulsePingSender pingSender; private final QuickPulseDataFetcher dataFetcher; private final QuickPulseDataSender dataSender; private final long waitBetweenPingsInMillis; private final long waitBetweenPostsInMillis; private final long waitOnErrorInMillis; QuickPulseCoordinator(QuickPulseCoordinatorInitData initData) { dataSender = initData.dataSender; pingSender = initData.pingSender; dataFetcher = initData.dataFetcher; collector = initData.collector; waitBetweenPingsInMillis = initData.waitBetweenPingsInMillis; waitBetweenPostsInMillis = initData.waitBetweenPostsInMillis; waitOnErrorInMillis = initData.waitOnErrorInMillis; qpsServiceRedirectedEndpoint = null; qpsServicePollingIntervalHintMillis = -1; } @Override @SuppressWarnings("try") private long sendData() { dataFetcher.prepareQuickPulseDataForSend(qpsServiceRedirectedEndpoint); QuickPulseHeaderInfo currentQuickPulseHeaderInfo = dataSender.getQuickPulseHeaderInfo(); this.handleReceivedHeaders(currentQuickPulseHeaderInfo); collector.setQuickPulseStatus(currentQuickPulseHeaderInfo.getQuickPulseStatus()); switch (currentQuickPulseHeaderInfo.getQuickPulseStatus()) { case ERROR: pingMode = true; return waitOnErrorInMillis; case QP_IS_OFF: pingMode = true; return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; case QP_IS_ON: return waitBetweenPostsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_SEND_ERROR.makeActive()) { logger.error("Critical error while sending QP data: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } @SuppressWarnings("try") private long ping() { QuickPulseHeaderInfo pingResult = pingSender.ping(qpsServiceRedirectedEndpoint); this.handleReceivedHeaders(pingResult); collector.setQuickPulseStatus(pingResult.getQuickPulseStatus()); switch (pingResult.getQuickPulseStatus()) { case ERROR: return waitOnErrorInMillis; case QP_IS_ON: pingMode = false; dataSender.startSending(); return waitBetweenPostsInMillis; case QP_IS_OFF: return qpsServicePollingIntervalHintMillis > 0 ? qpsServicePollingIntervalHintMillis : waitBetweenPingsInMillis; } try (MDC.MDCCloseable ignored = QUICK_PULSE_PING_ERROR.makeActive()) { logger.error("Critical error while ping QP: unknown status, aborting"); } collector.disable(); stopped = true; return 0; } private void handleReceivedHeaders(QuickPulseHeaderInfo currentQuickPulseHeaderInfo) { String redirectLink = currentQuickPulseHeaderInfo.getQpsServiceEndpointRedirect(); if (!Strings.isNullOrEmpty(redirectLink)) { qpsServiceRedirectedEndpoint = redirectLink; } long newPollingInterval = currentQuickPulseHeaderInfo.getQpsServicePollingInterval(); if (newPollingInterval > 0) { qpsServicePollingIntervalHintMillis = newPollingInterval; } } void stop() { stopped = true; } }
We should check that `readTimeout` is not null.
public InputStreamWithReadTimeout(InputStream delegate, Duration readTimeout) { this.delegate = delegate; this.readTimeout = readTimeout; this.hasTimeout = !readTimeout.isNegative() && !readTimeout.isZero(); }
this.hasTimeout = !readTimeout.isNegative() && !readTimeout.isZero();
public InputStreamWithReadTimeout(InputStream delegate, Duration readTimeout) { this.delegate = delegate; this.readTimeout = readTimeout; this.hasTimeout = readTimeout != null && !readTimeout.isNegative() && !readTimeout.isZero(); }
class InputStreamWithReadTimeout extends InputStream { private final Duration readTimeout; private final boolean hasTimeout; private final InputStream delegate; /** * Creates an {@link InputStream} that wraps an existing {@link InputStream} and provides read operations with a * timeout. * * @param delegate The {@link InputStream} to wrap. * @param readTimeout The read timeout. */ @Override public int read() throws IOException { if (hasTimeout) { Future<Integer> readOp = SharedExecutorService.getInstance().submit(() -> delegate.read()); return getResultWithTimeout(readOp, readTimeout); } else { return delegate.read(); } } @Override public int read(byte[] b) throws IOException { if (hasTimeout) { Future<Integer> readOp = SharedExecutorService.getInstance().submit(() -> delegate.read(b)); return getResultWithTimeout(readOp, readTimeout); } else { return delegate.read(b); } } @Override public int read(byte[] b, int off, int len) throws IOException { if (hasTimeout) { Future<Integer> readOp = SharedExecutorService.getInstance().submit(() -> delegate.read(b, off, len)); return getResultWithTimeout(readOp, readTimeout); } else { return delegate.read(b, off, len); } } @Override public long skip(long n) throws IOException { if (hasTimeout) { Future<Long> readOp = SharedExecutorService.getInstance().submit(() -> delegate.skip(n)); return getResultWithTimeout(readOp, readTimeout); } else { return delegate.skip(n); } } @Override public int available() throws IOException { return delegate.available(); } @Override public void close() throws IOException { delegate.close(); } @Override public void mark(int readlimit) { delegate.mark(readlimit); } @Override public void reset() throws IOException { delegate.reset(); } @Override public boolean markSupported() { return delegate.markSupported(); } private static <T> T getResultWithTimeout(Future<T> future, Duration timeout) throws IOException { try { return CoreUtils.getResultWithTimeout(future, timeout); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } catch (TimeoutException e) { throw new HttpTimeoutException("Timeout reading response body."); } } }
class InputStreamWithReadTimeout extends InputStream { private final Duration readTimeout; private final boolean hasTimeout; private final InputStream delegate; /** * Creates an {@link InputStream} that wraps an existing {@link InputStream} and provides read operations with a * timeout. * * @param delegate The {@link InputStream} to wrap. * @param readTimeout The read timeout. */ @Override public int read() throws IOException { if (hasTimeout) { Future<Integer> readOp = SharedExecutorService.getInstance().submit(() -> delegate.read()); return getResultWithTimeout(readOp, readTimeout); } else { return delegate.read(); } } @Override public int read(byte[] b) throws IOException { Objects.requireNonNull(b, "'b' cannot be null."); return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { Objects.checkFromIndexSize(off, len, b.length); if (hasTimeout) { int toRead = Math.min(len, 8192); Future<Integer> readOp = SharedExecutorService.getInstance().submit(() -> delegate.read(b, off, toRead)); return getResultWithTimeout(readOp, readTimeout); } else { return delegate.read(b, off, len); } } @Override public long skip(long n) throws IOException { long remaining = n; int bytesRead; if (n <= 0) { return 0; } int size = (int) Math.min(8192, remaining); byte[] skipBuffer = new byte[size]; while (remaining > 0) { bytesRead = read(skipBuffer, 0, (int) Math.min(size, remaining)); if (bytesRead < 0) { break; } remaining -= bytesRead; } return n - remaining; } @Override public int available() throws IOException { return delegate.available(); } @Override public void close() throws IOException { delegate.close(); } @Override public void mark(int readlimit) { delegate.mark(readlimit); } @Override public void reset() throws IOException { delegate.reset(); } @Override public boolean markSupported() { return delegate.markSupported(); } private static <T> T getResultWithTimeout(Future<T> future, Duration timeout) throws IOException { try { return CoreUtils.getResultWithTimeout(future, timeout); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } catch (TimeoutException e) { throw new HttpTimeoutException("Timeout reading response body."); } } }
@heyams I pushed this to show an option that avoids relying on the (confusing to me at least) `additionalProperties` (here's the full commit I pushed: https://github.com/Azure/azure-sdk-for-java/pull/41106/commits/75f6fe2845fb0e22d7a73afdf1d3beedc3723f2c)
private static void validateSpan(TelemetryItem telemetryItem) throws IOException { assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData"); RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); assertThat(actualData.getName()).isEqualTo("test"); assertThat(actualData.getProperties()) .containsExactly(entry("color", "red"), entry("name", "apple")); }
RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData());
private static void validateSpan(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData"); RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); assertThat(actualData.getName()).isEqualTo("test"); assertThat(actualData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); }
class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test public void testBuildTraceExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(10); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); HttpPipeline httpPipeline = getHttpPipeline(customValidationPolicy); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(httpPipeline, getConfiguration()); for (int i = 0; i < 10; i++) { generateSpan(openTelemetry); } countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(10); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); validateSpan(spanTelemetryItem); } @Test public void testBuildMetricExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateMetric(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); validateMetric(customValidationPolicy.getActualTelemetryItems().get(0)); } @Test public void testBuildLogExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateLog(openTelemetry); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateLog(logTelemetryItem); } @Test public void testBuildTraceMetricLogExportersConsecutively() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(3); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateSpan(openTelemetry); generateMetric(openTelemetry); generateLog(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(3); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); TelemetryItem metricTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Metric")) .findFirst() .get(); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateSpan(spanTelemetryItem); validateMetric(metricTelemetryItem); validateLog(logTelemetryItem); } @SuppressWarnings("try") private static void generateSpan(OpenTelemetry openTelemetry) { Tracer tracer = openTelemetry.getTracer("Sample"); Span span = tracer.spanBuilder("test").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAttribute("name", "apple"); span.setAttribute("color", "red"); } finally { span.end(); } } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static void generateLog(OpenTelemetry openTelemetry) { Logger logger = openTelemetry.getLogsBridge().get("Sample"); logger .logRecordBuilder() .setBody("test body") .setAttribute(AttributeKey.stringKey("name"), "apple") .setAttribute(AttributeKey.stringKey("color"), "red") .emit(); } @SuppressWarnings("unchecked") private static void validateMetric(TelemetryItem telemetryItem) { assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); Map<String, Object> metricData = ((List<Map<String, Object>>) telemetryItem.getData().getBaseData().getAdditionalProperties().get("metrics")).get(0); assertThat((Double) metricData.get("value")).isEqualTo(1.0); assertThat((String) metricData.get("name")).isEqualTo("test"); assertThat((Map<String, String>) telemetryItem.getData().getBaseData().getAdditionalProperties().get("properties")) .containsExactly(entry("color", "red"), entry("name", "apple")); } @SuppressWarnings("unchecked") private static void validateLog(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("Message"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MessageData"); Map<String, Object> messageProperties = telemetryItem.getData().getBaseData().getAdditionalProperties(); assertThat(messageProperties.get("message")).isEqualTo("test body"); assertThat((Map<String, String>) messageProperties.get("properties")) .containsOnly( entry("LoggerName", "Sample"), entry("SourceType", "Logger"), entry("color", "red"), entry("name", "apple")); } private static Map<String, String> getConfiguration() { return Collections.singletonMap("APPLICATIONINSIGHTS_CONNECTION_STRING", CONNECTION_STRING_ENV); } private static RemoteDependencyData toRemoteDependencyData(MonitorDomain baseData) throws IOException { return RemoteDependencyData.fromJson(JsonProviders.createReader(baseData.toJsonString())); } }
class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test public void testBuildTraceExporter() throws Exception { final int numberOfSpans = 10; CountDownLatch countDownLatch = new CountDownLatch(numberOfSpans); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); HttpPipeline httpPipeline = getHttpPipeline(customValidationPolicy); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(httpPipeline, getConfiguration()); for (int i = 0; i < numberOfSpans; i++) { generateSpan(openTelemetry); } countDownLatch.await(numberOfSpans, SECONDS); Thread.sleep(1000); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(numberOfSpans); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); validateSpan(spanTelemetryItem); } @Test public void testBuildMetricExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateMetric(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); validateMetric(customValidationPolicy.getActualTelemetryItems().get(0)); } @Test public void testBuildLogExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateLog(openTelemetry); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateLog(logTelemetryItem); } @Test public void testBuildTraceMetricLogExportersConsecutively() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(3); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateSpan(openTelemetry); generateMetric(openTelemetry); generateLog(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(3); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); TelemetryItem metricTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Metric")) .findFirst() .get(); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateSpan(spanTelemetryItem); validateMetric(metricTelemetryItem); validateLog(logTelemetryItem); } @SuppressWarnings("try") private static void generateSpan(OpenTelemetry openTelemetry) { Tracer tracer = openTelemetry.getTracer("Sample"); Span span = tracer.spanBuilder("test").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAttribute("name", "apple"); span.setAttribute("color", "red"); } finally { span.end(); } } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static void generateLog(OpenTelemetry openTelemetry) { Logger logger = openTelemetry.getLogsBridge().get("Sample"); logger .logRecordBuilder() .setBody("test body") .setAttribute(AttributeKey.stringKey("name"), "apple") .setAttribute(AttributeKey.stringKey("color"), "red") .emit(); } private static void validateMetric(TelemetryItem telemetryItem) { assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().size()).isEqualTo(1); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("test"); assertThat(metricsData.getMetrics().get(0).getValue()).isEqualTo(1.0); assertThat(metricsData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateLog(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("Message"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MessageData"); MessageData messageData = toMessageData(telemetryItem.getData().getBaseData()); assertThat(messageData.getMessage()).isEqualTo("test body"); assertThat(messageData.getProperties()) .containsOnly( entry("LoggerName", "Sample"), entry("SourceType", "Logger"), entry("color", "red"), entry("name", "apple")); } private static Map<String, String> getConfiguration() { return Collections.singletonMap("APPLICATIONINSIGHTS_CONNECTION_STRING", CONNECTION_STRING_ENV); } }
let's cache the pool although I just noticed that it looks like we stopped putting used byte buffers back into the pool a long time ago (tracked down to https://github.com/microsoft/ApplicationInsights-Java/pull/2091), which means we aren't getting any benefit from pooling, oops
private static ByteBufferOutputStream writeTelemetryItemsAsByteBufferOutputStream(List<TelemetryItem> telemetryItems) throws IOException { try (ByteBufferOutputStream result = new ByteBufferOutputStream(new AppInsightsByteBufferPool())) { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(result); for (int i = 0; i < telemetryItems.size(); i++) { JsonWriter jsonWriter = JsonProviders.createWriter(gzipOutputStream); telemetryItems.get(i).toJson(jsonWriter); jsonWriter.flush(); if (i < telemetryItems.size() - 1) { gzipOutputStream.write('\n'); } } gzipOutputStream.close(); return result; } }
try (ByteBufferOutputStream result = new ByteBufferOutputStream(new AppInsightsByteBufferPool())) {
private static ByteBufferOutputStream writeTelemetryItemsAsByteBufferOutputStream(List<TelemetryItem> telemetryItems) throws IOException { try (ByteBufferOutputStream result = new ByteBufferOutputStream(new AppInsightsByteBufferPool())) { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(result); for (int i = 0; i < telemetryItems.size(); i++) { JsonWriter jsonWriter = JsonProviders.createWriter(gzipOutputStream); telemetryItems.get(i).toJson(jsonWriter); jsonWriter.flush(); if (i < telemetryItems.size() - 1) { gzipOutputStream.write('\n'); } } gzipOutputStream.close(); return result; } }
class TelemetryItemExporter { private static final int MAX_CONCURRENT_EXPORTS = 100; private static final String _OTELRESOURCE_ = "_OTELRESOURCE_"; private static final OperationLogger operationLogger = new OperationLogger( TelemetryItemExporter.class, "Put export into the background (don't wait for it to return)"); private static final OperationLogger encodeBatchOperationLogger = new OperationLogger(TelemetryItemExporter.class, "Encoding telemetry batch into json"); private final TelemetryPipeline telemetryPipeline; private final TelemetryPipelineListener listener; private final Set<CompletableResultCode> activeExportResults = Collections.newSetFromMap(new ConcurrentHashMap<>()); public TelemetryItemExporter( TelemetryPipeline telemetryPipeline, TelemetryPipelineListener listener) { this.telemetryPipeline = telemetryPipeline; this.listener = listener; } public CompletableResultCode send(List<TelemetryItem> telemetryItems) { Map<TelemetryItemBatchKey, List<TelemetryItem>> batches = splitIntoBatches(telemetryItems); List<CompletableResultCode> resultCodeList = new ArrayList<>(); for (Map.Entry<TelemetryItemBatchKey, List<TelemetryItem>> batch : batches.entrySet()) { resultCodeList.add(internalSendByBatch(batch.getKey(), batch.getValue())); } maybeAddToActiveExportResults(resultCodeList); return CompletableResultCode.ofAll(resultCodeList); } Map<TelemetryItemBatchKey, List<TelemetryItem>> splitIntoBatches( List<TelemetryItem> telemetryItems) { Map<TelemetryItemBatchKey, List<TelemetryItem>> groupings = new HashMap<>(); for (TelemetryItem telemetryItem : telemetryItems) { TelemetryItemBatchKey telemetryItemBatchKey = new TelemetryItemBatchKey( telemetryItem.getConnectionString(), telemetryItem.getResource(), telemetryItem.getResourceFromTags() ); groupings .computeIfAbsent(telemetryItemBatchKey, k -> new ArrayList<>()) .add(telemetryItem); } return groupings; } private void maybeAddToActiveExportResults(List<CompletableResultCode> results) { if (activeExportResults.size() >= MAX_CONCURRENT_EXPORTS) { operationLogger.recordFailure( "Hit max " + MAX_CONCURRENT_EXPORTS + " active concurrent requests", TELEMETRY_ITEM_EXPORTER_ERROR); } operationLogger.recordSuccess(); activeExportResults.addAll(results); for (CompletableResultCode result : results) { result.whenComplete(() -> activeExportResults.remove(result)); } } public CompletableResultCode flush() { return CompletableResultCode.ofAll(activeExportResults); } public CompletableResultCode shutdown() { return listener.shutdown(); } CompletableResultCode internalSendByBatch(TelemetryItemBatchKey telemetryItemBatchKey, List<TelemetryItem> telemetryItems) { List<ByteBuffer> byteBuffers; if (!"Statsbeat".equals(telemetryItems.get(0).getName()) && AksResourceAttributes.isAks(telemetryItemBatchKey.resource)) { telemetryItems.add(0, createOtelResourceMetric(telemetryItemBatchKey)); } try { byteBuffers = serialize(telemetryItems); encodeBatchOperationLogger.recordSuccess(); } catch (Throwable t) { encodeBatchOperationLogger.recordFailure(t.getMessage(), t); return CompletableResultCode.ofFailure(); } return telemetryPipeline.send(byteBuffers, telemetryItemBatchKey.connectionString, listener); } private static List<ByteBuffer> serialize(List<TelemetryItem> telemetryItems) { try { ByteBufferOutputStream out = writeTelemetryItemsAsByteBufferOutputStream(telemetryItems); out.close(); List<ByteBuffer> byteBuffers = out.getByteBuffers(); for (ByteBuffer byteBuffer : byteBuffers) { byteBuffer.flip(); } return out.getByteBuffers(); } catch (IOException e) { throw new IllegalStateException("Failed to serialize list of TelemetryItems to List<ByteBuffer>", e); } } private TelemetryItem createOtelResourceMetric(TelemetryItemBatchKey telemetryItemBatchKey) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(_OTELRESOURCE_, 0); builder.setConnectionString(telemetryItemBatchKey.connectionString); telemetryItemBatchKey.resource.getAttributes().forEach((k, v) -> builder.addProperty(k.getKey(), v.toString())); String roleName = telemetryItemBatchKey.resourceFromTags.get(ContextTagKeys.AI_CLOUD_ROLE.toString()); if (roleName != null) { builder.addProperty(ServiceAttributes.SERVICE_NAME.getKey(), roleName); builder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), roleName); } String roleInstance = telemetryItemBatchKey.resourceFromTags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE.toString()); if (roleInstance != null) { builder.addProperty(ServiceIncubatingAttributes.SERVICE_INSTANCE_ID.getKey(), roleInstance); builder.addTag(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE.toString(), roleInstance); } String internalSdkVersion = telemetryItemBatchKey.resourceFromTags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString()); if (internalSdkVersion != null) { builder.addTag(ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString(), internalSdkVersion); } return builder.build(); } private static class TelemetryItemBatchKey { private final String connectionString; private final Resource resource; private final Map<String, String> resourceFromTags; private TelemetryItemBatchKey(String connectionString, Resource resource, Map<String, String> resourceFromTags) { this.connectionString = connectionString; this.resource = resource; this.resourceFromTags = resourceFromTags; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } TelemetryItemBatchKey that = (TelemetryItemBatchKey) other; return Objects.equals(connectionString, that.connectionString) && Objects.equals(resource, that.resource) && Objects.equals(resourceFromTags, that.resourceFromTags); } @Override public int hashCode() { return Objects.hash(connectionString, resource, resourceFromTags); } } }
class TelemetryItemExporter { private static final int MAX_CONCURRENT_EXPORTS = 100; private static final String _OTELRESOURCE_ = "_OTELRESOURCE_"; private static final OperationLogger operationLogger = new OperationLogger( TelemetryItemExporter.class, "Put export into the background (don't wait for it to return)"); private static final OperationLogger encodeBatchOperationLogger = new OperationLogger(TelemetryItemExporter.class, "Encoding telemetry batch into json"); private final TelemetryPipeline telemetryPipeline; private final TelemetryPipelineListener listener; private final Set<CompletableResultCode> activeExportResults = Collections.newSetFromMap(new ConcurrentHashMap<>()); public TelemetryItemExporter( TelemetryPipeline telemetryPipeline, TelemetryPipelineListener listener) { this.telemetryPipeline = telemetryPipeline; this.listener = listener; } public CompletableResultCode send(List<TelemetryItem> telemetryItems) { Map<TelemetryItemBatchKey, List<TelemetryItem>> batches = splitIntoBatches(telemetryItems); List<CompletableResultCode> resultCodeList = new ArrayList<>(); for (Map.Entry<TelemetryItemBatchKey, List<TelemetryItem>> batch : batches.entrySet()) { resultCodeList.add(internalSendByBatch(batch.getKey(), batch.getValue())); } maybeAddToActiveExportResults(resultCodeList); return CompletableResultCode.ofAll(resultCodeList); } Map<TelemetryItemBatchKey, List<TelemetryItem>> splitIntoBatches( List<TelemetryItem> telemetryItems) { Map<TelemetryItemBatchKey, List<TelemetryItem>> groupings = new HashMap<>(); for (TelemetryItem telemetryItem : telemetryItems) { TelemetryItemBatchKey telemetryItemBatchKey = new TelemetryItemBatchKey( telemetryItem.getConnectionString(), telemetryItem.getResource(), telemetryItem.getResourceFromTags() ); groupings .computeIfAbsent(telemetryItemBatchKey, k -> new ArrayList<>()) .add(telemetryItem); } return groupings; } private void maybeAddToActiveExportResults(List<CompletableResultCode> results) { if (activeExportResults.size() >= MAX_CONCURRENT_EXPORTS) { operationLogger.recordFailure( "Hit max " + MAX_CONCURRENT_EXPORTS + " active concurrent requests", TELEMETRY_ITEM_EXPORTER_ERROR); } operationLogger.recordSuccess(); activeExportResults.addAll(results); for (CompletableResultCode result : results) { result.whenComplete(() -> activeExportResults.remove(result)); } } public CompletableResultCode flush() { return CompletableResultCode.ofAll(activeExportResults); } public CompletableResultCode shutdown() { return listener.shutdown(); } CompletableResultCode internalSendByBatch(TelemetryItemBatchKey telemetryItemBatchKey, List<TelemetryItem> telemetryItems) { List<ByteBuffer> byteBuffers; if (!"Statsbeat".equals(telemetryItems.get(0).getName()) && AksResourceAttributes.isAks(telemetryItemBatchKey.resource)) { telemetryItems.add(0, createOtelResourceMetric(telemetryItemBatchKey)); } try { byteBuffers = serialize(telemetryItems); encodeBatchOperationLogger.recordSuccess(); } catch (Throwable t) { encodeBatchOperationLogger.recordFailure(t.getMessage(), t); return CompletableResultCode.ofFailure(); } return telemetryPipeline.send(byteBuffers, telemetryItemBatchKey.connectionString, listener); } private static List<ByteBuffer> serialize(List<TelemetryItem> telemetryItems) { try { ByteBufferOutputStream out = writeTelemetryItemsAsByteBufferOutputStream(telemetryItems); out.close(); List<ByteBuffer> byteBuffers = out.getByteBuffers(); for (ByteBuffer byteBuffer : byteBuffers) { byteBuffer.flip(); } return out.getByteBuffers(); } catch (IOException e) { throw new IllegalStateException("Failed to serialize list of TelemetryItems to List<ByteBuffer>", e); } } private TelemetryItem createOtelResourceMetric(TelemetryItemBatchKey telemetryItemBatchKey) { MetricTelemetryBuilder builder = MetricTelemetryBuilder.create(_OTELRESOURCE_, 0); builder.setConnectionString(telemetryItemBatchKey.connectionString); telemetryItemBatchKey.resource.getAttributes().forEach((k, v) -> builder.addProperty(k.getKey(), v.toString())); String roleName = telemetryItemBatchKey.resourceFromTags.get(ContextTagKeys.AI_CLOUD_ROLE.toString()); if (roleName != null) { builder.addProperty(ServiceAttributes.SERVICE_NAME.getKey(), roleName); builder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), roleName); } String roleInstance = telemetryItemBatchKey.resourceFromTags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE.toString()); if (roleInstance != null) { builder.addProperty(ServiceIncubatingAttributes.SERVICE_INSTANCE_ID.getKey(), roleInstance); builder.addTag(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE.toString(), roleInstance); } String internalSdkVersion = telemetryItemBatchKey.resourceFromTags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString()); if (internalSdkVersion != null) { builder.addTag(ContextTagKeys.AI_INTERNAL_SDK_VERSION.toString(), internalSdkVersion); } return builder.build(); } private static class TelemetryItemBatchKey { private final String connectionString; private final Resource resource; private final Map<String, String> resourceFromTags; private TelemetryItemBatchKey(String connectionString, Resource resource, Map<String, String> resourceFromTags) { this.connectionString = connectionString; this.resource = resource; this.resourceFromTags = resourceFromTags; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } TelemetryItemBatchKey that = (TelemetryItemBatchKey) other; return Objects.equals(connectionString, that.connectionString) && Objects.equals(resource, that.resource) && Objects.equals(resourceFromTags, that.resourceFromTags); } @Override public int hashCode() { return Objects.hash(connectionString, resource, resourceFromTags); } } }
```suggestion assertThat(expectedMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(actualMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); ```
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(10000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); String expected = Resources.readString("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected.getBytes(StandardCharsets.UTF_8)); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] decodedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(decodedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(actualMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
assertThat(actualMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue();
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(1000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); byte[] expected = Resources.readBytes("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] ungzippedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(ungzippedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(actualMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(new Comparator<TelemetryItem>() { @Override public int compare(TelemetryItem o1, TelemetryItem o2) { String name1, name2; try { name1 = toMetricsData(o1.getData().getBaseData()).getMetrics().get(0).getName(); name2 = toMetricsData(o2.getData().getBaseData()).getMetrics().get(0).getName(); return name1.compareTo(name2); } catch (IOException e) { throw new RuntimeException(e); } } }); } }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(Comparator.comparing(telemetryItem -> toMetricsData(telemetryItem.getData().getBaseData()).getMetrics().get(0).getName())); } }
```suggestion assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")); ```
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(10000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); String expected = Resources.readString("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected.getBytes(StandardCharsets.UTF_8)); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] decodedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(decodedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(actualMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline");
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(1000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); byte[] expected = Resources.readBytes("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] ungzippedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(ungzippedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(actualMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(new Comparator<TelemetryItem>() { @Override public int compare(TelemetryItem o1, TelemetryItem o2) { String name1, name2; try { name1 = toMetricsData(o1.getData().getBaseData()).getMetrics().get(0).getName(); name2 = toMetricsData(o2.getData().getBaseData()).getMetrics().get(0).getName(); return name1.compareTo(name2); } catch (IOException e) { throw new RuntimeException(e); } } }); } }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(Comparator.comparing(telemetryItem -> toMetricsData(telemetryItem.getData().getBaseData()).getMetrics().get(0).getName())); } }
```suggestion byte[] unzippedRawBytes = ungzip(file.rawBytes.array()); ```
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(10000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); String expected = Resources.readString("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected.getBytes(StandardCharsets.UTF_8)); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] decodedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(decodedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(actualMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
byte[] decodedRawBytes = ungzip(file.rawBytes.array());
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(1000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); byte[] expected = Resources.readBytes("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] ungzippedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(ungzippedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(actualMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(new Comparator<TelemetryItem>() { @Override public int compare(TelemetryItem o1, TelemetryItem o2) { String name1, name2; try { name1 = toMetricsData(o1.getData().getBaseData()).getMetrics().get(0).getName(); name2 = toMetricsData(o2.getData().getBaseData()).getMetrics().get(0).getName(); return name1.compareTo(name2); } catch (IOException e) { throw new RuntimeException(e); } } }); } }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(Comparator.comparing(telemetryItem -> toMetricsData(telemetryItem.getData().getBaseData()).getMetrics().get(0).getName())); } }
10 seconds is kind of long sleep to require in tests, if it's needed that's ok but maybe just add comment why ```suggestion Thread.sleep(1000); ```
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(10000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); String expected = Resources.readString("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected.getBytes(StandardCharsets.UTF_8)); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] decodedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(decodedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(actualMetricsData.getMetrics().get(0).getName().startsWith("to_be_persisted_offline_metric2" + i)).isTrue(); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
Thread.sleep(10000);
public void statusCode206Test() throws Exception { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (int i = 0; i < 100; i++) { String metricName = "metric" + i; if (i >= 20 && i <= 26) { metricName = "to_be_persisted_offline_metric" + i; } TelemetryItem item = TestUtils.createMetricTelemetry(metricName, i, CONNECTION_STRING, "state", "to_be_persisted_offline"); item.setTime(OffsetDateTime.parse("2024-05-31T00:00:00.00Z")); telemetryItems.add(item); } telemetryItemExporter.send(telemetryItems); telemetryItemExporter.flush().join(30, SECONDS); Thread.sleep(1000); LocalFileCache localFileCache = new LocalFileCache(tempFolder); LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, LocalStorageStats.noop(), false); assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(1); byte[] expected = Resources.readBytes("request_body_result_to_206_status_code.txt"); List<TelemetryItem> expectedTelemetryItems = deserialize(expected); LocalFileLoader.PersistedFile file = localFileLoader.loadTelemetriesFromDisk(); assertThat(file.connectionString).isEqualTo(CONNECTION_STRING); byte[] ungzippedRawBytes = ungzip(file.rawBytes.array()); List<TelemetryItem> actualTelemetryItems = deserialize(ungzippedRawBytes); assertThat(actualTelemetryItems.size()).isEqualTo(expectedTelemetryItems.size()); sort(expectedTelemetryItems); sort(actualTelemetryItems); for (int i = 0; i < actualTelemetryItems.size(); i++) { MetricsData expectedMetricsData = toMetricsData(expectedTelemetryItems.get(i).getData().getBaseData()); MetricsData actualMetricsData = toMetricsData(actualTelemetryItems.get(i).getData().getBaseData()); assertThat(expectedMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(actualMetricsData.getMetrics().get(0).getName()).startsWith("to_be_persisted_offline_metric2" + i); assertThat(expectedMetricsData.getMetrics().get(0).getName()).isEqualTo(actualMetricsData.getMetrics().get(0).getName()); assertThat(expectedMetricsData.getMetrics().get(0).getValue()).isEqualTo(actualMetricsData.getMetrics().get(0).getValue()); assertThat(expectedMetricsData.getMetrics().get(0).getCount()).isEqualTo(actualMetricsData.getMetrics().get(0).getCount()); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(actualMetricsData.getProperties().get("state")).isEqualTo("to_be_persisted_offline"); assertThat(expectedMetricsData.getProperties().get("state")).isEqualTo(actualMetricsData.getProperties().get("state")); } assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0); }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(new Comparator<TelemetryItem>() { @Override public int compare(TelemetryItem o1, TelemetryItem o2) { String name1, name2; try { name1 = toMetricsData(o1.getData().getBaseData()).getMetrics().get(0).getName(); name2 = toMetricsData(o2.getData().getBaseData()).getMetrics().get(0).getName(); return name1.compareTo(name2); } catch (IOException e) { throw new RuntimeException(e); } } }); } }
class Handle206Test { private static final String CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http: private TelemetryItemExporter telemetryItemExporter; @TempDir File tempFolder; @BeforeEach public void setup() { HttpClient mockedClient; final String[] mockedResponseBody = new String[1]; mockedClient = httpRequest -> { try { mockedResponseBody[0] = Resources.readString("206_response_body.txt"); } catch (IOException e) { throw new RuntimeException(e); } return Mono.just(new MockHttpResponse(httpRequest, 206, mockedResponseBody[0].getBytes())); }; HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder() .httpClient(mockedClient) .tracer(new NoopTracer()); TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build(), null); telemetryItemExporter = new TelemetryItemExporter( telemetryPipeline, new LocalStorageTelemetryPipelineListener( 50, tempFolder, telemetryPipeline, LocalStorageStats.noop(), false)); } @Test private static void sort(List<TelemetryItem> telemetryItems) { telemetryItems.sort(Comparator.comparing(telemetryItem -> toMetricsData(telemetryItem.getData().getBaseData()).getMetrics().get(0).getName())); } }
maybe we should just change `toMetricsData` (and friends) to catch IOException and rethrow RuntimeException? then wouldn't need to handle here
private void verifyStatsbeatTelemetry(CustomValidationPolicy customValidationPolicy) throws IOException { TelemetryItem attachStatsbeat = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Statsbeat")) .filter(item -> { MetricsData metricsData = null; try { metricsData = toMetricsData(item.getData().getBaseData()); } catch (IOException e) { throw new RuntimeException(e); } return metricsData.getMetrics().get(0).getName().equals("Attach"); }) .findFirst() .get(); validateAttachStatsbeat(attachStatsbeat); TelemetryItem featureStatsbeat = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Statsbeat")) .filter(item -> { MetricsData metricsData = null; try { metricsData = toMetricsData(item.getData().getBaseData()); } catch (IOException e) { throw new RuntimeException(e); } return metricsData.getMetrics().get(0).getName().equals("Feature"); }) .findFirst() .get(); validateFeatureStatsbeat(featureStatsbeat); }
}
private void verifyStatsbeatTelemetry(CustomValidationPolicy customValidationPolicy) { TelemetryItem attachStatsbeat = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Statsbeat")) .filter(item -> { return toMetricsData(item.getData().getBaseData()).getMetrics().get(0).getName().equals("Attach"); }) .findFirst() .get(); validateAttachStatsbeat(attachStatsbeat); TelemetryItem featureStatsbeat = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Statsbeat")) .filter(item -> { return toMetricsData(item.getData().getBaseData()).getMetrics().get(0).getName().equals("Feature"); }) .findFirst() .get(); validateFeatureStatsbeat(featureStatsbeat); }
class AzureMonitorStatsbeatTest { private static final String STATSBEAT_CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-000000000000;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test public void testStatsbeat() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy, HttpClient.createDefault()), getStatsbeatConfiguration(), STATSBEAT_CONNECTION_STRING); generateMetric(openTelemetry); openTelemetry.close(); Thread.sleep(2000); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: verifyStatsbeatTelemetry(customValidationPolicy); } @Test @DisabledOnOs(value = {OS.MAC}, disabledReason = "Unstable") public void testStatsbeatShutdownWhen400InvalidIKeyReturned() throws Exception { String fakeBody = "{\"itemsReceived\":4,\"itemsAccepted\":0,\"errors\":[{\"index\":0,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"},{\"index\":1,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"},{\"index\":2,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"},{\"index\":3,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"}]}"; verifyStatsbeatShutdownOrnNot(fakeBody, true); } @Test public void testStatsbeatNotShutDownWhen400InvalidDataReturned() throws Exception { String fakeBody = "{\"itemsReceived\":1,\"itemsAccepted\":0,\"errors\":[{\"index\":0,\"statusCode\":400,\"message\":\"102: Field 'time' on type 'Envelope' is not a valid time string. Expected: date, Actual: fake\"}]}"; verifyStatsbeatShutdownOrnNot(fakeBody, false); } private void verifyStatsbeatShutdownOrnNot(String fakeBody, boolean shutdown) throws Exception { MockedHttpClient mockedHttpClient = new MockedHttpClient( request -> { return Mono.just(new MockHttpResponse(request, 400, new HttpHeaders(), fakeBody.getBytes())); }); CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetrySdk = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy, mockedHttpClient), getStatsbeatConfiguration(), STATSBEAT_CONNECTION_STRING); generateMetric(openTelemetrySdk); openTelemetrySdk.close(); Thread.sleep(2000); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: if (shutdown) { assertThat(customValidationPolicy.getActualTelemetryItems().stream().filter(item -> item.getName().equals("Statsbeat")).count()).isEqualTo(0); } else { verifyStatsbeatTelemetry(customValidationPolicy); } } private HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy, HttpClient httpClient) { return new HttpPipelineBuilder() .httpClient(httpClient) .policies(policy == null ? new HttpPipelinePolicy[0] : new HttpPipelinePolicy[]{policy}) .tracer(new NoopTracer()) .build(); } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static Map<String, String> getStatsbeatConfiguration() { Map<String, String> map = new HashMap<>(3); map.put("APPLICATIONINSIGHTS_CONNECTION_STRING", STATSBEAT_CONNECTION_STRING); map.put("STATSBEAT_LONG_INTERVAL_SECONDS_PROPERTY_NAME", "1"); map.put("STATSBEAT_SHORT_INTERVAL_SECONDS_PROPERTY_NAME", "1"); return map; } private static void validateAttachStatsbeat(TelemetryItem telemetryItem) throws IOException { assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("Attach"); assertThat(metricsData.getProperties()).contains(entry("rp", "unknown"), entry("attach", "Manual"), entry("language", "java")); assertThat(metricsData.getProperties()).containsKeys("attach", "cikey", "language", "os", "rp", "runtimeVersion", "version"); } private static void validateFeatureStatsbeat(TelemetryItem telemetryItem) throws IOException { assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("Feature"); assertThat(metricsData.getProperties()).contains(entry("type", "0"), entry("language", "java")); assertThat(metricsData.getProperties()).containsKeys("feature", "cikey", "language", "os", "rp", "runtimeVersion", "version"); } private static class MockedHttpClient implements HttpClient { private final AtomicInteger count = new AtomicInteger(); private final Function<HttpRequest, Mono<HttpResponse>> handler; MockedHttpClient(Function<HttpRequest, Mono<HttpResponse>> handler) { this.handler = handler; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { count.getAndIncrement(); return handler.apply(httpRequest); } int getCount() { return count.get(); } } }
class AzureMonitorStatsbeatTest { private static final String STATSBEAT_CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-000000000000;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test public void testStatsbeat() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy, HttpClient.createDefault()), getStatsbeatConfiguration(), STATSBEAT_CONNECTION_STRING); generateMetric(openTelemetry); openTelemetry.close(); Thread.sleep(2000); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: verifyStatsbeatTelemetry(customValidationPolicy); } @Test @DisabledOnOs(value = {OS.MAC}, disabledReason = "Unstable") public void testStatsbeatShutdownWhen400InvalidIKeyReturned() throws Exception { String fakeBody = "{\"itemsReceived\":4,\"itemsAccepted\":0,\"errors\":[{\"index\":0,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"},{\"index\":1,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"},{\"index\":2,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"},{\"index\":3,\"statusCode\":400,\"message\":\"Invalid instrumentation key\"}]}"; verifyStatsbeatShutdownOrnNot(fakeBody, true); } @Test public void testStatsbeatNotShutDownWhen400InvalidDataReturned() throws Exception { String fakeBody = "{\"itemsReceived\":1,\"itemsAccepted\":0,\"errors\":[{\"index\":0,\"statusCode\":400,\"message\":\"102: Field 'time' on type 'Envelope' is not a valid time string. Expected: date, Actual: fake\"}]}"; verifyStatsbeatShutdownOrnNot(fakeBody, false); } private void verifyStatsbeatShutdownOrnNot(String fakeBody, boolean shutdown) throws Exception { MockedHttpClient mockedHttpClient = new MockedHttpClient( request -> { return Mono.just(new MockHttpResponse(request, 400, new HttpHeaders(), fakeBody.getBytes())); }); CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetrySdk = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy, mockedHttpClient), getStatsbeatConfiguration(), STATSBEAT_CONNECTION_STRING); generateMetric(openTelemetrySdk); openTelemetrySdk.close(); Thread.sleep(2000); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: if (shutdown) { assertThat(customValidationPolicy.getActualTelemetryItems().stream().filter(item -> item.getName().equals("Statsbeat")).count()).isEqualTo(0); } else { verifyStatsbeatTelemetry(customValidationPolicy); } } private HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy, HttpClient httpClient) { return new HttpPipelineBuilder() .httpClient(httpClient) .policies(policy == null ? new HttpPipelinePolicy[0] : new HttpPipelinePolicy[]{policy}) .tracer(new NoopTracer()) .build(); } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static Map<String, String> getStatsbeatConfiguration() { Map<String, String> map = new HashMap<>(3); map.put("APPLICATIONINSIGHTS_CONNECTION_STRING", STATSBEAT_CONNECTION_STRING); map.put("STATSBEAT_LONG_INTERVAL_SECONDS_PROPERTY_NAME", "1"); map.put("STATSBEAT_SHORT_INTERVAL_SECONDS_PROPERTY_NAME", "1"); return map; } private static void validateAttachStatsbeat(TelemetryItem telemetryItem) { assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("Attach"); assertThat(metricsData.getProperties()).contains(entry("rp", "unknown"), entry("attach", "Manual"), entry("language", "java")); assertThat(metricsData.getProperties()).containsKeys("attach", "cikey", "language", "os", "rp", "runtimeVersion", "version"); } private static void validateFeatureStatsbeat(TelemetryItem telemetryItem) { assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("Feature"); assertThat(metricsData.getProperties()).contains(entry("type", "0"), entry("language", "java")); assertThat(metricsData.getProperties()).containsKeys("feature", "cikey", "language", "os", "rp", "runtimeVersion", "version"); } private static class MockedHttpClient implements HttpClient { private final AtomicInteger count = new AtomicInteger(); private final Function<HttpRequest, Mono<HttpResponse>> handler; MockedHttpClient(Function<HttpRequest, Mono<HttpResponse>> handler) { this.handler = handler; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { count.getAndIncrement(); return handler.apply(httpRequest); } int getCount() { return count.get(); } } }
```suggestion for (int i = 0; i < numberOfSpans; i++) { ```
public void testBuildTraceExporter() throws Exception { final int numberOfSpans = 10; CountDownLatch countDownLatch = new CountDownLatch(numberOfSpans); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); HttpPipeline httpPipeline = getHttpPipeline(customValidationPolicy); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(httpPipeline, getConfiguration()); for (int i = 0; i < 10; i++) { generateSpan(openTelemetry); } countDownLatch.await(numberOfSpans, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(numberOfSpans); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); validateSpan(spanTelemetryItem); }
for (int i = 0; i < 10; i++) {
public void testBuildTraceExporter() throws Exception { final int numberOfSpans = 10; CountDownLatch countDownLatch = new CountDownLatch(numberOfSpans); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); HttpPipeline httpPipeline = getHttpPipeline(customValidationPolicy); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(httpPipeline, getConfiguration()); for (int i = 0; i < numberOfSpans; i++) { generateSpan(openTelemetry); } countDownLatch.await(numberOfSpans, SECONDS); Thread.sleep(1000); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(numberOfSpans); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); validateSpan(spanTelemetryItem); }
class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test @Test public void testBuildMetricExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateMetric(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); validateMetric(customValidationPolicy.getActualTelemetryItems().get(0)); } @Test public void testBuildLogExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateLog(openTelemetry); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateLog(logTelemetryItem); } @Test public void testBuildTraceMetricLogExportersConsecutively() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(3); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateSpan(openTelemetry); generateMetric(openTelemetry); generateLog(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(3); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); TelemetryItem metricTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Metric")) .findFirst() .get(); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateSpan(spanTelemetryItem); validateMetric(metricTelemetryItem); validateLog(logTelemetryItem); } @SuppressWarnings("try") private static void generateSpan(OpenTelemetry openTelemetry) { Tracer tracer = openTelemetry.getTracer("Sample"); Span span = tracer.spanBuilder("test").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAttribute("name", "apple"); span.setAttribute("color", "red"); } finally { span.end(); } } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static void generateLog(OpenTelemetry openTelemetry) { Logger logger = openTelemetry.getLogsBridge().get("Sample"); logger .logRecordBuilder() .setBody("test body") .setAttribute(AttributeKey.stringKey("name"), "apple") .setAttribute(AttributeKey.stringKey("color"), "red") .emit(); } private static void validateSpan(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData"); RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); assertThat(actualData.getName()).isEqualTo("test"); assertThat(actualData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateMetric(TelemetryItem telemetryItem) { assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().size()).isEqualTo(1); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("test"); assertThat(metricsData.getMetrics().get(0).getValue()).isEqualTo(1.0); assertThat(metricsData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateLog(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("Message"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MessageData"); MessageData messageData = toMessageData(telemetryItem.getData().getBaseData()); assertThat(messageData.getMessage()).isEqualTo("test body"); assertThat(messageData.getProperties()) .containsOnly( entry("LoggerName", "Sample"), entry("SourceType", "Logger"), entry("color", "red"), entry("name", "apple")); } private static Map<String, String> getConfiguration() { return Collections.singletonMap("APPLICATIONINSIGHTS_CONNECTION_STRING", CONNECTION_STRING_ENV); } }
class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test @Test public void testBuildMetricExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateMetric(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); validateMetric(customValidationPolicy.getActualTelemetryItems().get(0)); } @Test public void testBuildLogExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateLog(openTelemetry); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateLog(logTelemetryItem); } @Test public void testBuildTraceMetricLogExportersConsecutively() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(3); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateSpan(openTelemetry); generateMetric(openTelemetry); generateLog(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(3); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); TelemetryItem metricTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Metric")) .findFirst() .get(); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateSpan(spanTelemetryItem); validateMetric(metricTelemetryItem); validateLog(logTelemetryItem); } @SuppressWarnings("try") private static void generateSpan(OpenTelemetry openTelemetry) { Tracer tracer = openTelemetry.getTracer("Sample"); Span span = tracer.spanBuilder("test").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAttribute("name", "apple"); span.setAttribute("color", "red"); } finally { span.end(); } } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static void generateLog(OpenTelemetry openTelemetry) { Logger logger = openTelemetry.getLogsBridge().get("Sample"); logger .logRecordBuilder() .setBody("test body") .setAttribute(AttributeKey.stringKey("name"), "apple") .setAttribute(AttributeKey.stringKey("color"), "red") .emit(); } private static void validateSpan(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData"); RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); assertThat(actualData.getName()).isEqualTo("test"); assertThat(actualData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateMetric(TelemetryItem telemetryItem) { assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().size()).isEqualTo(1); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("test"); assertThat(metricsData.getMetrics().get(0).getValue()).isEqualTo(1.0); assertThat(metricsData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateLog(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("Message"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MessageData"); MessageData messageData = toMessageData(telemetryItem.getData().getBaseData()); assertThat(messageData.getMessage()).isEqualTo("test body"); assertThat(messageData.getProperties()) .containsOnly( entry("LoggerName", "Sample"), entry("SourceType", "Logger"), entry("color", "red"), entry("name", "apple")); } private static Map<String, String> getConfiguration() { return Collections.singletonMap("APPLICATIONINSIGHTS_CONNECTION_STRING", CONNECTION_STRING_ENV); } }
```suggestion // generate spans ```
public void testBuildTraceExporter() throws Exception { final int numberOfSpans = 10; CountDownLatch countDownLatch = new CountDownLatch(numberOfSpans); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); HttpPipeline httpPipeline = getHttpPipeline(customValidationPolicy); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(httpPipeline, getConfiguration()); for (int i = 0; i < 10; i++) { generateSpan(openTelemetry); } countDownLatch.await(numberOfSpans, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(numberOfSpans); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); validateSpan(spanTelemetryItem); }
public void testBuildTraceExporter() throws Exception { final int numberOfSpans = 10; CountDownLatch countDownLatch = new CountDownLatch(numberOfSpans); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); HttpPipeline httpPipeline = getHttpPipeline(customValidationPolicy); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk(httpPipeline, getConfiguration()); for (int i = 0; i < numberOfSpans; i++) { generateSpan(openTelemetry); } countDownLatch.await(numberOfSpans, SECONDS); Thread.sleep(1000); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(numberOfSpans); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); validateSpan(spanTelemetryItem); }
class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test @Test public void testBuildMetricExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateMetric(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); validateMetric(customValidationPolicy.getActualTelemetryItems().get(0)); } @Test public void testBuildLogExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateLog(openTelemetry); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateLog(logTelemetryItem); } @Test public void testBuildTraceMetricLogExportersConsecutively() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(3); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateSpan(openTelemetry); generateMetric(openTelemetry); generateLog(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(3); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); TelemetryItem metricTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Metric")) .findFirst() .get(); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateSpan(spanTelemetryItem); validateMetric(metricTelemetryItem); validateLog(logTelemetryItem); } @SuppressWarnings("try") private static void generateSpan(OpenTelemetry openTelemetry) { Tracer tracer = openTelemetry.getTracer("Sample"); Span span = tracer.spanBuilder("test").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAttribute("name", "apple"); span.setAttribute("color", "red"); } finally { span.end(); } } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static void generateLog(OpenTelemetry openTelemetry) { Logger logger = openTelemetry.getLogsBridge().get("Sample"); logger .logRecordBuilder() .setBody("test body") .setAttribute(AttributeKey.stringKey("name"), "apple") .setAttribute(AttributeKey.stringKey("color"), "red") .emit(); } private static void validateSpan(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData"); RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); assertThat(actualData.getName()).isEqualTo("test"); assertThat(actualData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateMetric(TelemetryItem telemetryItem) { assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().size()).isEqualTo(1); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("test"); assertThat(metricsData.getMetrics().get(0).getValue()).isEqualTo(1.0); assertThat(metricsData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateLog(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("Message"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MessageData"); MessageData messageData = toMessageData(telemetryItem.getData().getBaseData()); assertThat(messageData.getMessage()).isEqualTo("test body"); assertThat(messageData.getProperties()) .containsOnly( entry("LoggerName", "Sample"), entry("SourceType", "Logger"), entry("color", "red"), entry("name", "apple")); } private static Map<String, String> getConfiguration() { return Collections.singletonMap("APPLICATIONINSIGHTS_CONNECTION_STRING", CONNECTION_STRING_ENV); } }
class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https: + "LiveEndpoint=https: private static final String INSTRUMENTATION_KEY = "00000000-0000-0000-0000-000000000000"; @Test @Test public void testBuildMetricExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateMetric(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); validateMetric(customValidationPolicy.getActualTelemetryItems().get(0)); } @Test public void testBuildLogExporter() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(1); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetry openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateLog(openTelemetry); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(1); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateLog(logTelemetryItem); } @Test public void testBuildTraceMetricLogExportersConsecutively() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(3); CustomValidationPolicy customValidationPolicy = new CustomValidationPolicy(countDownLatch); OpenTelemetrySdk openTelemetry = TestUtils.createOpenTelemetrySdk( getHttpPipeline(customValidationPolicy), getConfiguration()); generateSpan(openTelemetry); generateMetric(openTelemetry); generateLog(openTelemetry); openTelemetry.close(); countDownLatch.await(10, SECONDS); assertThat(customValidationPolicy.getUrl()) .isEqualTo(new URL("https: assertThat(customValidationPolicy.getActualTelemetryItems().size()).isEqualTo(3); TelemetryItem spanTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("RemoteDependency")) .findFirst() .get(); TelemetryItem metricTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Metric")) .findFirst() .get(); TelemetryItem logTelemetryItem = customValidationPolicy.getActualTelemetryItems().stream() .filter(item -> item.getName().equals("Message")) .findFirst() .get(); validateSpan(spanTelemetryItem); validateMetric(metricTelemetryItem); validateLog(logTelemetryItem); } @SuppressWarnings("try") private static void generateSpan(OpenTelemetry openTelemetry) { Tracer tracer = openTelemetry.getTracer("Sample"); Span span = tracer.spanBuilder("test").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAttribute("name", "apple"); span.setAttribute("color", "red"); } finally { span.end(); } } private static void generateMetric(OpenTelemetry openTelemetry) { Meter meter = openTelemetry.getMeter("Sample"); LongCounter counter = meter.counterBuilder("test").build(); counter.add( 1L, Attributes.of( AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red")); } private static void generateLog(OpenTelemetry openTelemetry) { Logger logger = openTelemetry.getLogsBridge().get("Sample"); logger .logRecordBuilder() .setBody("test body") .setAttribute(AttributeKey.stringKey("name"), "apple") .setAttribute(AttributeKey.stringKey("color"), "red") .emit(); } private static void validateSpan(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData"); RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); assertThat(actualData.getName()).isEqualTo("test"); assertThat(actualData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateMetric(TelemetryItem telemetryItem) { assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MetricData"); MetricsData metricsData = toMetricsData(telemetryItem.getData().getBaseData()); assertThat(metricsData.getMetrics().size()).isEqualTo(1); assertThat(metricsData.getMetrics().get(0).getName()).isEqualTo("test"); assertThat(metricsData.getMetrics().get(0).getValue()).isEqualTo(1.0); assertThat(metricsData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple")); } private static void validateLog(TelemetryItem telemetryItem) { assertThat(telemetryItem.getName()).isEqualTo("Message"); assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY); assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java"); assertThat(telemetryItem.getTags()) .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel")); assertThat(telemetryItem.getData().getBaseType()).isEqualTo("MessageData"); MessageData messageData = toMessageData(telemetryItem.getData().getBaseData()); assertThat(messageData.getMessage()).isEqualTo("test body"); assertThat(messageData.getProperties()) .containsOnly( entry("LoggerName", "Sample"), entry("SourceType", "Logger"), entry("color", "red"), entry("name", "apple")); } private static Map<String, String> getConfiguration() { return Collections.singletonMap("APPLICATIONINSIGHTS_CONNECTION_STRING", CONNECTION_STRING_ENV); } }
this isn't needed ```suggestion ```
private static List<ByteBuffer> gzip(List<byte[]> byteArrayList) { try (ByteBufferOutputStream result = new ByteBufferOutputStream(new AppInsightsByteBufferPool())) { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(result); for (int i = 0; i < byteArrayList.size(); i++) { gzipOutputStream.write(byteArrayList.get(i)); if (i < byteArrayList.size() - 1) { gzipOutputStream.write('\n'); } } gzipOutputStream.close(); List<ByteBuffer> resultByteBuffers = result.getByteBuffers(); for (ByteBuffer byteBuffer : resultByteBuffers) { byteBuffer.flip(); } return result.getByteBuffers(); } catch (IOException e) { throw new IllegalArgumentException("Failed to encode list of ByteBuffers before persisting to the offline disk", e); } }
}
private static List<ByteBuffer> gzip(List<byte[]> byteArrayList) { try (ByteBufferOutputStream result = new ByteBufferOutputStream(new AppInsightsByteBufferPool())) { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(result); for (int i = 0; i < byteArrayList.size(); i++) { gzipOutputStream.write(byteArrayList.get(i)); if (i < byteArrayList.size() - 1) { gzipOutputStream.write('\n'); } } gzipOutputStream.close(); List<ByteBuffer> resultByteBuffers = result.getByteBuffers(); for (ByteBuffer byteBuffer : resultByteBuffers) { byteBuffer.flip(); } return result.getByteBuffers(); } catch (IOException e) { throw new IllegalArgumentException("Failed to encode list of ByteBuffers before persisting to the offline disk", e); } }
class LocalStorageTelemetryPipelineListener implements TelemetryPipelineListener { private static final ClientLogger logger = new ClientLogger(LocalStorageTelemetryPipelineListener.class); private final LocalFileWriter localFileWriter; private final LocalFileSender localFileSender; private final LocalFilePurger localFilePurger; private final AtomicBoolean shutdown = new AtomicBoolean(); public LocalStorageTelemetryPipelineListener( int diskPersistenceMaxSizeMb, File telemetryFolder, TelemetryPipeline pipeline, LocalStorageStats stats, boolean suppressWarnings) { LocalFileCache localFileCache = new LocalFileCache(telemetryFolder); LocalFileLoader loader = new LocalFileLoader(localFileCache, telemetryFolder, stats, suppressWarnings); localFileWriter = new LocalFileWriter( diskPersistenceMaxSizeMb, localFileCache, telemetryFolder, stats, suppressWarnings); long intervalSeconds = diskPersistenceMaxSizeMb > 50 ? 10 : 30; localFileSender = new LocalFileSender(intervalSeconds, loader, pipeline, suppressWarnings); localFilePurger = new LocalFilePurger(telemetryFolder, suppressWarnings); } @Override public void onResponse(TelemetryPipelineRequest request, TelemetryPipelineResponse response) { int statusCode = response.getStatusCode(); if (StatusCode.isRetryable(statusCode)) { localFileWriter.writeToDisk( request.getConnectionString(), request.getByteBuffers(), getOriginalErrorMessage(response)); } else if (statusCode == 206) { processStatusCode206(request, response); } } private void processStatusCode206(TelemetryPipelineRequest request, TelemetryPipelineResponse response) { Set<ResponseError> errors = response.getErrors(); errors.forEach(error -> logger.verbose("Error in telemetry: {}", error)); if (!errors.isEmpty()) { List<ByteBuffer> originalByteBuffers = request.getByteBuffers(); byte[] gzippedBytes = convertByteBufferListToByteArray(originalByteBuffers); byte[] ungzippedBytes = ungzip(gzippedBytes); List<byte[]> serializedTelemetryItemsByteArrayList = splitBytesByNewline(ungzippedBytes); List<byte[]> toBePersisted = new ArrayList<>(); for (ResponseError error : errors) { if (StatusCode.isRetryable(error.getStatusCode())) { toBePersisted.add(serializedTelemetryItemsByteArrayList.get(error.getIndex())); } } if (!toBePersisted.isEmpty()) { localFileWriter.writeToDisk( request.getConnectionString(), gzip(toBePersisted), "Received partial response code 206"); } } } private static byte[] convertByteBufferListToByteArray(List<ByteBuffer> byteBuffers) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (ByteBuffer buffer : byteBuffers) { byte[] arr = new byte[buffer.remaining()]; buffer.get(arr); try { baos.write(arr); } catch (IOException e) { throw new RuntimeException(e); } } return baos.toByteArray(); } public static byte[] ungzip(byte[] rawBytes) { try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(rawBytes)); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] data = new byte[1024]; int read; while ((read = in.read(data)) != -1) { baos.write(data, 0, read); } return baos.toByteArray(); } catch (IOException e) { throw new IllegalStateException("Failed to decode byte[]", e); } } private static List<byte[]> splitBytesByNewline(byte[] inputBytes) { List<byte[]> lines = new ArrayList<>(); int start = 0; for (int i = 0; i < inputBytes.length; i++) { if (inputBytes[i] == '\n') { byte[] line = new byte[i - start]; System.arraycopy(inputBytes, start, line, 0, i - start); lines.add(line); start = i + 1; } } if (start < inputBytes.length) { byte[] lastLine = new byte[inputBytes.length - start]; System.arraycopy(inputBytes, start, lastLine, 0, inputBytes.length - start); lines.add(lastLine); } return lines; } @Override public void onException( TelemetryPipelineRequest request, String errorMessage, Throwable throwable) { localFileWriter.writeToDisk(request.getConnectionString(), request.getByteBuffers(), errorMessage); } @Override public CompletableResultCode shutdown() { if (!shutdown.getAndSet(true)) { localFileSender.shutdown(); localFilePurger.shutdown(); } return CompletableResultCode.ofSuccess(); } private static String getOriginalErrorMessage(TelemetryPipelineResponse response) { int statusCode = response.getStatusCode(); if (statusCode == 401 || statusCode == 403) { return DiagnosticTelemetryPipelineListener .getErrorMessageFromCredentialRelatedResponse(statusCode, response.getBody()); } else { return "Received response code " + statusCode; } } }
class LocalStorageTelemetryPipelineListener implements TelemetryPipelineListener { private static final ClientLogger logger = new ClientLogger(LocalStorageTelemetryPipelineListener.class); private final LocalFileWriter localFileWriter; private final LocalFileSender localFileSender; private final LocalFilePurger localFilePurger; private final AtomicBoolean shutdown = new AtomicBoolean(); public LocalStorageTelemetryPipelineListener( int diskPersistenceMaxSizeMb, File telemetryFolder, TelemetryPipeline pipeline, LocalStorageStats stats, boolean suppressWarnings) { LocalFileCache localFileCache = new LocalFileCache(telemetryFolder); LocalFileLoader loader = new LocalFileLoader(localFileCache, telemetryFolder, stats, suppressWarnings); localFileWriter = new LocalFileWriter( diskPersistenceMaxSizeMb, localFileCache, telemetryFolder, stats, suppressWarnings); long intervalSeconds = diskPersistenceMaxSizeMb > 50 ? 10 : 30; localFileSender = new LocalFileSender(intervalSeconds, loader, pipeline, suppressWarnings); localFilePurger = new LocalFilePurger(telemetryFolder, suppressWarnings); } @Override public void onResponse(TelemetryPipelineRequest request, TelemetryPipelineResponse response) { int statusCode = response.getStatusCode(); if (StatusCode.isRetryable(statusCode)) { localFileWriter.writeToDisk( request.getConnectionString(), request.getByteBuffers(), getOriginalErrorMessage(response)); } else if (statusCode == 206) { processStatusCode206(request, response); } } private void processStatusCode206(TelemetryPipelineRequest request, TelemetryPipelineResponse response) { Set<ResponseError> errors = response.getErrors(); errors.forEach(error -> logger.verbose("Error in telemetry: {}", error)); if (!errors.isEmpty()) { List<ByteBuffer> originalByteBuffers = request.getByteBuffers(); byte[] gzippedBytes = convertByteBufferListToByteArray(originalByteBuffers); byte[] ungzippedBytes = ungzip(gzippedBytes); List<byte[]> serializedTelemetryItemsByteArrayList = splitBytesByNewline(ungzippedBytes); List<byte[]> toBePersisted = new ArrayList<>(); for (ResponseError error : errors) { if (StatusCode.isRetryable(error.getStatusCode())) { toBePersisted.add(serializedTelemetryItemsByteArrayList.get(error.getIndex())); } } if (!toBePersisted.isEmpty()) { localFileWriter.writeToDisk( request.getConnectionString(), gzip(toBePersisted), "Received partial response code 206"); } } } private static byte[] convertByteBufferListToByteArray(List<ByteBuffer> byteBuffers) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (ByteBuffer buffer : byteBuffers) { byte[] arr = new byte[buffer.remaining()]; buffer.get(arr); try { baos.write(arr); } catch (IOException e) { throw new RuntimeException(e); } } return baos.toByteArray(); } public static byte[] ungzip(byte[] rawBytes) { try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(rawBytes)); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] data = new byte[1024]; int read; while ((read = in.read(data)) != -1) { baos.write(data, 0, read); } return baos.toByteArray(); } catch (IOException e) { throw new IllegalStateException("Failed to decode byte[]", e); } } static List<byte[]> splitBytesByNewline(byte[] inputBytes) { List<byte[]> lines = new ArrayList<>(); int start = 0; for (int i = 0; i < inputBytes.length; i++) { if (inputBytes[i] == '\n') { lines.add(Arrays.copyOfRange(inputBytes, start, i)); start = i + 1; } } if (start < inputBytes.length) { lines.add(Arrays.copyOfRange(inputBytes, start, inputBytes.length)); } return lines; } @Override public void onException( TelemetryPipelineRequest request, String errorMessage, Throwable throwable) { localFileWriter.writeToDisk(request.getConnectionString(), request.getByteBuffers(), errorMessage); } @Override public CompletableResultCode shutdown() { if (!shutdown.getAndSet(true)) { localFileSender.shutdown(); localFilePurger.shutdown(); } return CompletableResultCode.ofSuccess(); } private static String getOriginalErrorMessage(TelemetryPipelineResponse response) { int statusCode = response.getStatusCode(); if (statusCode == 401 || statusCode == 403) { return DiagnosticTelemetryPipelineListener .getErrorMessageFromCredentialRelatedResponse(statusCode, response.getBody()); } else { return "Received response code " + statusCode; } } }
better to keep the `filter` in the method down below where it was previously
public Set<String> getErrorMessages() { Set<ResponseError> responseErrors; try { responseErrors = parseErrors(body); } catch (IllegalStateException e) { return singleton("Could not parse response"); } return responseErrors.stream().map(ResponseError::getMessage) .filter(message -> !message.equals("Telemetry sampled out.")) .collect(Collectors.toSet()); }
.filter(message -> !message.equals("Telemetry sampled out."))
public Set<String> getErrorMessages() { Set<ResponseError> responseErrors; try { responseErrors = parseErrors(body); } catch (IllegalStateException e) { return singleton("Could not parse response"); } return responseErrors.stream().map(ResponseError::getMessage).collect(Collectors.toSet()); }
class TelemetryPipelineResponse { private static final String INVALID_INSTRUMENTATION_KEY = "Invalid instrumentation key"; private final int statusCode; private final String body; TelemetryPipelineResponse(int statusCode, String body) { this.statusCode = statusCode; this.body = body; } public int getStatusCode() { return statusCode; } public String getBody() { return body; } public Set<ResponseError> getErrors() { try { return parseErrors(body); } catch (IllegalStateException e) { return emptySet(); } } public boolean isInvalidInstrumentationKey() { Set<String> errors = getErrorMessages(); return errors != null && errors.contains(INVALID_INSTRUMENTATION_KEY); } static Set<ResponseError> parseErrors(String body) { try (JsonReader reader = JsonProviders.createReader(body)) { Response response = Response.fromJson(reader); return new HashSet<>(response.getErrors()); } catch (IOException e) { throw new IllegalStateException("Failed to parse response body", e); } } }
class TelemetryPipelineResponse { private static final String INVALID_INSTRUMENTATION_KEY = "Invalid instrumentation key"; private final int statusCode; private final String body; TelemetryPipelineResponse(int statusCode, String body) { this.statusCode = statusCode; this.body = body; } public int getStatusCode() { return statusCode; } public String getBody() { return body; } public Set<ResponseError> getErrors() { try { return parseErrors(body); } catch (IllegalStateException e) { return emptySet(); } } public boolean isInvalidInstrumentationKey() { Set<String> errors = getErrorMessages(); return errors != null && errors.contains(INVALID_INSTRUMENTATION_KEY); } static Set<ResponseError> parseErrors(String body) { try (JsonReader reader = JsonProviders.createReader(body)) { Response response = Response.fromJson(reader); return response.getErrors().stream() .filter(error -> !error.getMessage().equals("Telemetry sampled out.")) .collect(Collectors.toSet()); } catch (IOException e) { throw new IllegalStateException("Failed to parse response body", e); } } }
should the default value be `false`? instead of using` !`?
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return !DEFAULT_PREVENT_INVALID_ID_CHARS; }
return !DEFAULT_PREVENT_INVALID_ID_CHARS;
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_PREVENT_INVALID_ID_CHARS; }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = true; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = false; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
@FabianMeiswinkel - I also think the default should be `false` - otherwise, while debugging this becomes an issue when we see the default value set as `true`. Someone might easily miss this `!defaultValue` :)
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return !DEFAULT_PREVENT_INVALID_ID_CHARS; }
return !DEFAULT_PREVENT_INVALID_ID_CHARS;
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_PREVENT_INVALID_ID_CHARS; }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = true; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = false; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
Sorry - I do not get this? Reading simple conditional statements is something any developer can do?
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return !DEFAULT_PREVENT_INVALID_ID_CHARS; }
return !DEFAULT_PREVENT_INVALID_ID_CHARS;
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_PREVENT_INVALID_ID_CHARS; }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = true; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = false; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
If we change default value we would also need to change meaning/name of the variables - I can do it but really do not see where the problem is?
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return !DEFAULT_PREVENT_INVALID_ID_CHARS; }
return !DEFAULT_PREVENT_INVALID_ID_CHARS;
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_PREVENT_INVALID_ID_CHARS; }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = true; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = false; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
Fixed
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return !DEFAULT_PREVENT_INVALID_ID_CHARS; }
return !DEFAULT_PREVENT_INVALID_ID_CHARS;
public static boolean isIdValueValidationEnabled() { String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return !Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return!Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_PREVENT_INVALID_ID_CHARS; }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = true; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); /** * Integer value specifying the speculation type * <pre> * 0 - No speculation * 1 - Threshold based speculation * </pre> */ public static final String SPECULATION_TYPE = "COSMOS_SPECULATION_TYPE"; public static final String SPECULATION_THRESHOLD = "COSMOS_SPECULATION_THRESHOLD"; public static final String SPECULATION_THRESHOLD_STEP = "COSMOS_SPECULATION_THRESHOLD_STEP"; private final SslContext sslContext; private static final String PROTOCOL_ENVIRONMENT_VARIABLE = "AZURE_COSMOS_DIRECT_MODE_PROTOCOL"; private static final String PROTOCOL_PROPERTY = "azure.cosmos.directModeProtocol"; private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; private static final String MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES"; private static final String MAX_HTTP_CHUNK_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_CHUNK_SIZE_IN_BYTES"; private static final String MAX_HTTP_HEADER_SIZE_IN_BYTES = "COSMOS.MAX_HTTP_HEADER_SIZE_IN_BYTES"; private static final String MAX_DIRECT_HTTPS_POOL_SIZE = "COSMOS.MAX_DIRECT_HTTP_CONNECTION_LIMIT"; private static final String HTTP_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.HTTP_RESPONSE_TIMEOUT_IN_SECONDS"; public static final int DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE = 1000; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; public static final int DEFAULT_HTTP_MAX_REQUEST_TIMEOUT = 60; public static final String HTTP_MAX_REQUEST_TIMEOUT = "COSMOS.HTTP_MAX_REQUEST_TIMEOUT"; public static final String HTTP_MAX_REQUEST_TIMEOUT_VARIABLE = "COSMOS_HTTP_MAX_REQUEST_TIMEOUT"; private static final String QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS"; private static final String ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = "COSMOS.ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY = "COSMOS.WRITE_RETRY_POLICY"; public static final String NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE = "COSMOS_WRITE_RETRY_POLICY"; private static final String CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG = "COSMOS.CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG"; private static final String CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = "COSMOS.CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS"; private static final String CLIENT_TELEMETRY_ENDPOINT = "COSMOS.CLIENT_TELEMETRY_ENDPOINT"; private static final String ENVIRONMENT_NAME = "COSMOS.ENVIRONMENT_NAME"; private static final String QUERYPLAN_CACHING_ENABLED = "COSMOS.QUERYPLAN_CACHING_ENABLED"; private static final int DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS = 10 * 60; private static final int DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = 5 * 60; private static final int DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES = 6 * 1024 * 1024; private static final int DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH = 4096; private static final int DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES = 8192; private static final int DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE = 32 * 1024; private static final int MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_PRIMARY_READ_RETRIES = 6; private static final int MAX_NUMBER_OF_READ_QUORUM_RETRIES = 6; private static final int DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS = 5; private static final int MAX_BARRIER_RETRIES_FOR_MULTI_REGION = 30; private static final int BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 30; private static final int MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION = 4; private static final int SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION = 10; private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; private static final int DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = 2 * 60; private static final Duration MAX_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(45); private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; private static final int DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS = 60; private static final int DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS = 5; private static final int DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS = 5000; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS = 5; public static final String DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS"; private static final int DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS = 500; public static final int MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 100; private static final String DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME = "COSMOS.DEFAULT_SESSION_TOKEN_MISMATCH_IN_REGION-RETRY_TIME_IN_MILLISECONDS"; private static final int DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS = 500; public static final String SESSION_CAPTURING_TYPE = "COSMOS.SESSION_CAPTURING_TYPE"; public static final String DEFAULT_SESSION_CAPTURING_TYPE = StringUtils.EMPTY; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT"; private static final long DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT = 5_000_000; public static final String PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME = "COSMOS.PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE"; private static final double DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE = 0.001; private static final String SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME = "COSMOS.SWITCH_OFF_IO_THREAD_FOR_RESPONSE"; private static final boolean DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE = false; private static final String QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = "COSMOS.QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED"; private static final boolean DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED = false; private static final String USE_LEGACY_TRACING = "COSMOS.USE_LEGACY_TRACING"; private static final boolean DEFAULT_USE_LEGACY_TRACING = false; private static final String REPLICA_ADDRESS_VALIDATION_ENABLED = "COSMOS.REPLICA_ADDRESS_VALIDATION_ENABLED"; private static final boolean DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED = true; private static final String TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = "COSMOS.TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED"; private static final boolean DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED = true; private static final String MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = "COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"; private static final int DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT = 1; private static final String MAX_TRACE_MESSAGE_LENGTH = "COSMOS.MAX_TRACE_MESSAGE_LENGTH"; private static final int DEFAULT_MAX_TRACE_MESSAGE_LENGTH = 32 * 1024; private static final int MIN_MAX_TRACE_MESSAGE_LENGTH = 8 * 1024; private static final String AGGRESSIVE_WARMUP_CONCURRENCY = "COSMOS.AGGRESSIVE_WARMUP_CONCURRENCY"; private static final int DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY = Configs.getCPUCnt(); private static final String OPEN_CONNECTIONS_CONCURRENCY = "COSMOS.OPEN_CONNECTIONS_CONCURRENCY"; private static final int DEFAULT_OPEN_CONNECTIONS_CONCURRENCY = 1; public static final String MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = "COSMOS.MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED"; private static final int DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; private static final String MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = "COSMOS.MAX_ITEM_SIZE_FOR_VECTOR_SEARCH"; public static final int DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH = 50000; private static final String AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = "COSMOS.AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY"; private static final boolean DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY = false; public static final int MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED = 1; public static final String TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS = "COSMOS.TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS"; public static final String DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = "COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"; public static final boolean DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR = true; public static final String PREVENT_INVALID_ID_CHARS = "COSMOS.PREVENT_INVALID_ID_CHARS"; public static final String PREVENT_INVALID_ID_CHARS_VARIABLE = "COSMOS_PREVENT_INVALID_ID_CHARS"; public static final boolean DEFAULT_PREVENT_INVALID_ID_CHARS = false; public static final String METRICS_CONFIG = "COSMOS.METRICS_CONFIG"; public static final String DEFAULT_METRICS_CONFIG = CosmosMicrometerMetricsConfig.DEFAULT.toJson(); public Configs() { this.sslContext = sslContextInit(); } public static int getCPUCnt() { return CPU_CNT; } private SslContext sslContextInit() { try { SslProvider sslProvider = SslContext.defaultClientProvider(); return SslContextBuilder.forClient().sslProvider(sslProvider).build(); } catch (SSLException sslException) { logger.error("Fatal error cannot instantiate ssl context due to {}", sslException.getMessage(), sslException); throw new IllegalStateException(sslException); } } public SslContext getSslContext() { return this.sslContext; } public Protocol getProtocol() { String protocol = System.getProperty(PROTOCOL_PROPERTY, firstNonNull( emptyToNull(System.getenv().get(PROTOCOL_ENVIRONMENT_VARIABLE)), DEFAULT_PROTOCOL.name())); try { return Protocol.valueOf(protocol.toUpperCase(Locale.ROOT)); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; } } public int getMaxNumberOfReadBarrierReadRetries() { return MAX_NUMBER_OF_READ_BARRIER_READ_RETRIES; } public int getMaxNumberOfPrimaryReadRetries() { return MAX_NUMBER_OF_PRIMARY_READ_RETRIES; } public int getMaxNumberOfReadQuorumRetries() { return MAX_NUMBER_OF_READ_QUORUM_RETRIES; } public int getDelayBetweenReadBarrierCallsInMs() { return DELAY_BETWEEN_READ_BARRIER_CALLS_IN_MS; } public int getMaxBarrierRetriesForMultiRegion() { return MAX_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getBarrierRetryIntervalInMsForMultiRegion() { return BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getMaxShortBarrierRetriesForMultiRegion() { return MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION; } public int getShortBarrierRetryIntervalInMsForMultiRegion() { return SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION; } public int getDirectHttpsMaxConnectionLimit() { return getJVMConfigAsInt(MAX_DIRECT_HTTPS_POOL_SIZE, DEFAULT_DIRECT_HTTPS_POOL_SIZE); } public int getMaxHttpHeaderSize() { return getJVMConfigAsInt(MAX_HTTP_HEADER_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_REQUEST_HEADER_SIZE); } public int getMaxHttpInitialLineLength() { return getJVMConfigAsInt(MAX_HTTP_INITIAL_LINE_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_INITIAL_LINE_LENGTH); } public int getMaxHttpChunkSize() { return getJVMConfigAsInt(MAX_HTTP_CHUNK_SIZE_IN_BYTES, DEFAULT_MAX_HTTP_CHUNK_SIZE_IN_BYTES); } public int getMaxHttpBodyLength() { return getJVMConfigAsInt(MAX_HTTP_BODY_LENGTH_IN_BYTES, DEFAULT_MAX_HTTP_BODY_LENGTH_IN_BYTES); } public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } public static int getClientTelemetrySchedulingInSec() { return getJVMConfigAsInt(CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS, DEFAULT_CLIENT_TELEMETRY_SCHEDULING_IN_SECONDS); } public int getGlobalEndpointManagerMaxInitializationTimeInSeconds() { return getJVMConfigAsInt(GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS, DEFAULT_GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS); } public String getReactorNettyConnectionPoolName() { return REACTOR_NETTY_CONNECTION_POOL_NAME; } public Duration getMaxIdleConnectionTimeout() { return MAX_IDLE_CONNECTION_TIMEOUT; } public Duration getConnectionAcquireTimeout() { return CONNECTION_ACQUIRE_TIMEOUT; } public static int getHttpResponseTimeoutInSeconds() { return getJVMConfigAsInt(HTTP_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_HTTP_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getQueryPlanResponseTimeoutInSeconds() { return getJVMConfigAsInt(QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_QUERY_PLAN_RESPONSE_TIMEOUT_IN_SECONDS); } public static String getClientTelemetryEndpoint() { return System.getProperty(CLIENT_TELEMETRY_ENDPOINT); } public static String getClientTelemetryProxyOptionsConfig() { return System.getProperty(CLIENT_TELEMETRY_PROXY_OPTIONS_CONFIG); } public static String getNonIdempotentWriteRetryPolicy() { String valueFromSystemProperty = System.getProperty(NON_IDEMPOTENT_WRITE_RETRY_POLICY); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return valueFromSystemProperty; } return System.getenv(NON_IDEMPOTENT_WRITE_RETRY_POLICY_VARIABLE); } public static int getDefaultHttpPoolSize() { String valueFromSystemProperty = System.getProperty(HTTP_DEFAULT_CONNECTION_POOL_SIZE); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Boolean.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Boolean.valueOf(valueFromEnvVariable); } return DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT; } public static int getMaxHttpRequestTimeout() { String valueFromSystemProperty = System.getProperty(HTTP_MAX_REQUEST_TIMEOUT); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { return Integer.valueOf(valueFromSystemProperty); } String valueFromEnvVariable = System.getenv(HTTP_MAX_REQUEST_TIMEOUT_VARIABLE); if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { return Integer.valueOf(valueFromEnvVariable); } return DEFAULT_HTTP_MAX_REQUEST_TIMEOUT; } public static String getEnvironmentName() { return System.getProperty(ENVIRONMENT_NAME); } public static boolean isQueryPlanCachingEnabled() { return getJVMConfigAsBoolean(QUERYPLAN_CACHING_ENABLED, true); } public static int getAddressRefreshResponseTimeoutInSeconds() { return getJVMConfigAsInt(ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS, DEFAULT_ADDRESS_REFRESH_RESPONSE_TIMEOUT_IN_SECONDS); } public static int getSessionTokenMismatchDefaultWaitTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_WAIT_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchInitialBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_INITIAL_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSessionTokenMismatchMaximumBackoffTimeInMs() { return getJVMConfigAsInt( DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS_NAME, DEFAULT_SESSION_TOKEN_MISMATCH_MAXIMUM_BACKOFF_TIME_IN_MILLISECONDS); } public static int getSpeculationType() { return getJVMConfigAsInt(SPECULATION_TYPE, 0); } public static int speculationThreshold() { return getJVMConfigAsInt(SPECULATION_THRESHOLD, 500); } public static int speculationThresholdStep() { return getJVMConfigAsInt(SPECULATION_THRESHOLD_STEP, 100); } public static boolean shouldSwitchOffIOThreadForResponse() { return getJVMConfigAsBoolean( SWITCH_OFF_IO_THREAD_FOR_RESPONSE_NAME, DEFAULT_SWITCH_OFF_IO_THREAD_FOR_RESPONSE); } public static boolean isEmptyPageDiagnosticsEnabled() { return getJVMConfigAsBoolean( QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED, DEFAULT_QUERY_EMPTY_PAGE_DIAGNOSTICS_ENABLED); } public static boolean useLegacyTracing() { return getJVMConfigAsBoolean( USE_LEGACY_TRACING, DEFAULT_USE_LEGACY_TRACING); } private static int getJVMConfigAsInt(String propName, int defaultValue) { String propValue = System.getProperty(propName); return getIntValue(propValue, defaultValue); } private static boolean getJVMConfigAsBoolean(String propName, boolean defaultValue) { String propValue = System.getProperty(propName); return getBooleanValue(propValue, defaultValue); } private static int getIntValue(String val, int defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Integer.valueOf(val); } } private static boolean getBooleanValue(String val, boolean defaultValue) { if (StringUtils.isEmpty(val)) { return defaultValue; } else { return Boolean.valueOf(val); } } public static boolean isReplicaAddressValidationEnabled() { return getJVMConfigAsBoolean( REPLICA_ADDRESS_VALIDATION_ENABLED, DEFAULT_REPLICA_ADDRESS_VALIDATION_ENABLED); } public static boolean isTcpHealthCheckTimeoutDetectionEnabled() { return getJVMConfigAsBoolean( TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED, DEFAULT_TCP_HEALTH_CHECK_TIMEOUT_DETECTION_ENABLED); } public static int getMinConnectionPoolSizePerEndpoint() { return getIntValue(System.getProperty(MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT), DEFAULT_MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT); } public static int getOpenConnectionsConcurrency() { return getIntValue(System.getProperty(OPEN_CONNECTIONS_CONCURRENCY), DEFAULT_OPEN_CONNECTIONS_CONCURRENCY); } public static int getAggressiveWarmupConcurrency() { return getIntValue(System.getProperty(AGGRESSIVE_WARMUP_CONCURRENCY), DEFAULT_AGGRESSIVE_WARMUP_CONCURRENCY); } public static int getMaxRetriesInLocalRegionWhenRemoteRegionPreferred() { return Math.max( getIntValue( System.getProperty(MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), DEFAULT_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED), MIN_MAX_RETRIES_IN_LOCAL_REGION_WHEN_REMOTE_REGION_PREFERRED); } public static int getMaxItemCountForVectorSearch() { return Integer.parseInt(System.getProperty(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH, firstNonNull( emptyToNull(System.getenv().get(MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)), String.valueOf(DEFAULT_MAX_ITEM_COUNT_FOR_VECTOR_SEARCH)))); } public static boolean getAzureCosmosNonStreamingOrderByDisabled() { if(logger.isTraceEnabled()) { logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY property is: {}", System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); logger.trace( "AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY env variable is: {}", System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)); } return Boolean.parseBoolean(System.getProperty(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY, firstNonNull( emptyToNull(System.getenv().get(AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)), String.valueOf(DEFAULT_AZURE_COSMOS_DISABLE_NON_STREAMING_ORDER_BY)))); } public static Duration getMinRetryTimeInLocalRegionWhenRemoteRegionPreferred() { return Duration.ofMillis(Math.max( getIntValue( System.getProperty(DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS_NAME), DEFAULT_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS), MIN_MIN_IN_REGION_RETRY_TIME_FOR_WRITES_MS)); } public static int getMaxTraceMessageLength() { return Math.max( getIntValue( System.getProperty(MAX_TRACE_MESSAGE_LENGTH), DEFAULT_MAX_TRACE_MESSAGE_LENGTH), MIN_MAX_TRACE_MESSAGE_LENGTH); } public static Duration getTcpConnectionAcquisitionTimeout(int defaultValueInMs) { return Duration.ofMillis( getIntValue( System.getProperty(TCP_CONNECTION_ACQUISITION_TIMEOUT_IN_MS), defaultValueInMs ) ); } public static String getSessionCapturingType() { return System.getProperty( SESSION_CAPTURING_TYPE, firstNonNull( emptyToNull(System.getenv().get(SESSION_CAPTURING_TYPE)), DEFAULT_SESSION_CAPTURING_TYPE)); } public static long getPkBasedBloomFilterExpectedInsertionCount() { String pkBasedBloomFilterExpectedInsertionCount = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_INSERTION_COUNT))); return Long.parseLong(pkBasedBloomFilterExpectedInsertionCount); } public static double getPkBasedBloomFilterExpectedFfpRate() { String pkBasedBloomFilterExpectedFfpRate = System.getProperty( PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME, firstNonNull( emptyToNull(System.getenv().get(PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE_NAME)), String.valueOf(DEFAULT_PK_BASED_BLOOM_FILTER_EXPECTED_FFP_RATE))); return Double.parseDouble(pkBasedBloomFilterExpectedFfpRate); } public static boolean shouldDiagnosticsProviderSystemExitOnError() { String shouldSystemExit = System.getProperty( DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR, firstNonNull( emptyToNull(System.getenv().get(DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR)), String.valueOf(DEFAULT_DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR))); return Boolean.parseBoolean(shouldSystemExit); } public static CosmosMicrometerMetricsConfig getMetricsConfig() { String metricsConfig = System.getProperty( METRICS_CONFIG, firstNonNull( emptyToNull(System.getenv().get(METRICS_CONFIG)), DEFAULT_METRICS_CONFIG)); return CosmosMicrometerMetricsConfig.fromJsonString(metricsConfig); } }
I think the query parameter start is in the wrong spot, shouldn't it be after the queue name as that is part of the URL path? ```suggestion String queueURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, QUEUE_NAME, SAS_TOKEN); ```
public static void main(String[] args) { String queueURL = String.format("https: QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueURL).buildAsyncClient(); queueAsyncClient.create() .doOnSuccess(response -> queueAsyncClient.sendMessage("This is message 1")) .then(queueAsyncClient.sendMessage("This is message 2")) .subscribe( response -> System.out.println( "Message successfully equeueed by queueAsyncClient. Message id:" + response.getMessageId()), err -> System.out.println("Error thrown when enqueue the message. Error message: " + err.getMessage()), () -> System.out.println("The enqueue has been completed.")); }
String queueURL = String.format("https:
public static void main(String[] args) { String queueURL = String.format("https: QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueURL).buildAsyncClient(); queueAsyncClient.create() .doOnSuccess(response -> queueAsyncClient.sendMessage("This is message 1")) .then(queueAsyncClient.sendMessage("This is message 2")) .subscribe( response -> System.out.println( "Message successfully equeueed by queueAsyncClient. Message id:" + response.getMessageId()), err -> System.out.println("Error thrown when enqueue the message. Error message: " + err.getMessage()), () -> System.out.println("The enqueue has been completed.")); }
class AsyncSamples { private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); private static final String QUEUE_NAME = generateRandomName("async-call", 16); /** * The main method shows how we do the basic operations of enqueueing and dequeueing messages on async queue client. * @param args No args needed for main method. */ }
class AsyncSamples { private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); private static final String QUEUE_NAME = generateRandomName("async-call", 16); /** * The main method shows how we do the basic operations of enqueueing and dequeueing messages on async queue client. * @param args No args needed for main method. */ }
same
public void authorizationCodeCredentialsCodeSnippets() { TokenCredential authorizationCodeCredential = new AuthorizationCodeCredentialBuilder() .authorizationCode("{authorization-code-received-at-redirectURL}") .redirectUrl("{redirectUrl-where-authorization-code-is-received}") .clientId("{clientId-of-application-being-authenticated") .build(); } /** * Method to insert code snippets for {@link OnBehalfOfCredential} */ public void oboCredentialsCodeSnippets() { TokenCredential onBehalfOfCredential = new OnBehalfOfCredentialBuilder() .clientId("<app-client-ID>") .clientSecret("<app-Client-Secret>") .tenantId("<app-tenant-ID>") .userAssertion("<user-assertion>") .build(); } /** * Method to insert code snippets for {@link WorkloadIdentityCredential} */ public void workloadIdentityCredentialCodeSnippets() { TokenCredential workloadIdentityCredential = new WorkloadIdentityCredentialBuilder() .clientId("<clientID>") .tenantId("<tenantID>") .tokenFilePath("<token-file-path>") .build(); } /** * Method to insert code snippets for {@link AzureDeveloperCliCredential} */ public void azureDeveloperCliCredentialCodeSnippets() { TokenCredential azureDevCliCredential = new AzureDeveloperCliCredentialBuilder() .build(); } public void azurePipelinesCredentialCodeSnippets() { String systemAccessToken = System.getenv("SYSTEM_ACCESSTOKEN"); AzurePipelinesCredential credential = new AzurePipelinesCredentialBuilder() .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .systemAccessToken(systemAccessToken) .build(); } public void silentAuthenticationSnippets() { String authenticationRecordPath = "path/to/authentication-record.json"; AuthenticationRecord authenticationRecord = null; try { if (Files.exists(new File(authenticationRecordPath).toPath())) { authenticationRecord = AuthenticationRecord.deserialize(new FileInputStream(authenticationRecordPath)); } } catch (FileNotFoundException e) { } DeviceCodeCredentialBuilder builder = new DeviceCodeCredentialBuilder() .clientId(clientId) .tenantId(tenantId) .challengeConsumer(challenge -> { System.out.println(challenge.getMessage()); }); if (authenticationRecord != null) { builder.authenticationRecord(authenticationRecord); } DeviceCodeCredential credential = builder.build(); TokenRequestContext trc = new TokenRequestContext().addScopes("your-appropriate-scope"); if (authenticationRecord == null) { credential.authenticate(trc).flatMap(record -> { try { return record.serializeAsync(new FileOutputStream(authenticationRecordPath)); } catch (FileNotFoundException e) { return Mono.error(e); } }).subscribe(); } AccessToken token = credential.getTokenSync(trc); } }
.challengeConsumer(challenge -> {
public void authorizationCodeCredentialsCodeSnippets() { TokenCredential authorizationCodeCredential = new AuthorizationCodeCredentialBuilder() .authorizationCode("{authorization-code-received-at-redirectURL}") .redirectUrl("{redirectUrl-where-authorization-code-is-received}") .clientId("{clientId-of-application-being-authenticated") .build(); } /** * Method to insert code snippets for {@link OnBehalfOfCredential} */ public void oboCredentialsCodeSnippets() { TokenCredential onBehalfOfCredential = new OnBehalfOfCredentialBuilder() .clientId("<app-client-ID>") .clientSecret("<app-Client-Secret>") .tenantId("<app-tenant-ID>") .userAssertion("<user-assertion>") .build(); } /** * Method to insert code snippets for {@link WorkloadIdentityCredential} */ public void workloadIdentityCredentialCodeSnippets() { TokenCredential workloadIdentityCredential = new WorkloadIdentityCredentialBuilder() .clientId("<clientID>") .tenantId("<tenantID>") .tokenFilePath("<token-file-path>") .build(); } /** * Method to insert code snippets for {@link AzureDeveloperCliCredential} */ public void azureDeveloperCliCredentialCodeSnippets() { TokenCredential azureDevCliCredential = new AzureDeveloperCliCredentialBuilder() .build(); } public void azurePipelinesCredentialCodeSnippets() { String systemAccessToken = System.getenv("SYSTEM_ACCESSTOKEN"); AzurePipelinesCredential credential = new AzurePipelinesCredentialBuilder() .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .systemAccessToken(systemAccessToken) .build(); } public void silentAuthenticationSnippets() { String authenticationRecordPath = "path/to/authentication-record.json"; AuthenticationRecord authenticationRecord = null; try { if (Files.exists(new File(authenticationRecordPath).toPath())) { authenticationRecord = AuthenticationRecord.deserialize(new FileInputStream(authenticationRecordPath)); } } catch (FileNotFoundException e) { } DeviceCodeCredentialBuilder builder = new DeviceCodeCredentialBuilder() .clientId(clientId) .tenantId(tenantId); if (authenticationRecord != null) { builder.authenticationRecord(authenticationRecord); } DeviceCodeCredential credential = builder.build(); TokenRequestContext trc = new TokenRequestContext().addScopes("your-appropriate-scope"); if (authenticationRecord == null) { credential.authenticate(trc).flatMap(record -> { try { return record.serializeAsync(new FileOutputStream(authenticationRecordPath)); } catch (FileNotFoundException e) { return Mono.error(e); } }).subscribe(); } AccessToken token = credential.getTokenSync(trc); } }
class JavaDocCodeSnippets { private String tenantId = System.getenv("AZURE_TENANT_ID"); private String clientId = System.getenv("AZURE_CLIENT_ID"); private String clientSecret = System.getenv("AZURE_CLIENT_SECRET"); private String serviceConnectionId = System.getenv("SERVICE_CONNECTION_ID"); private String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; private String fakePasswordPlaceholder = "fakePasswordPlaceholder"; /** * Method to insert code snippets for {@link ClientSecretCredential} */ public void clientSecretCredentialCodeSnippets() { TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build(); TokenCredential secretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientCertificateCredential} */ public void clientCertificateCredentialCodeSnippets() { TokenCredential clientCertificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate("<PATH-TO-PEM-CERTIFICATE>") .build(); byte[] certificateBytes = new byte[0]; ByteArrayInputStream certificateStream = new ByteArrayInputStream(certificateBytes); TokenCredential certificateCredentialWithStream = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificateStream) .build(); TokenCredential certificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pfxCertificate("<PATH-TO-PFX-CERTIFICATE>", "P@s$w0rd") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientAssertionCredential} */ public void clientAssertionCredentialCodeSnippets() { TokenCredential clientAssertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .build(); TokenCredential assertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ChainedTokenCredential} */ public void chainedTokenCredentialCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId(clientId) .username(fakeUsernamePlaceholder) .password(fakePasswordPlaceholder) .build(); TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .clientId(clientId) .port(8765) .build(); TokenCredential credential = new ChainedTokenCredentialBuilder() .addLast(usernamePasswordCredential) .addLast(interactiveBrowserCredential) .build(); } /** * Method to insert code snippets for {@link DefaultAzureCredential} */ public void defaultAzureCredentialCodeSnippets() { TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder() .build(); TokenCredential dacWithUserAssignedManagedIdentity = new DefaultAzureCredentialBuilder() .managedIdentityClientId("<Managed-Identity-Client-Id") .build(); } /** * Method to insert code snippets for {@link InteractiveBrowserCredential} */ public void interactiveBrowserCredentialsCodeSnippets() { TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .redirectUrl("http: .build(); } /** * Method to insert code snippets for {@link ManagedIdentityCredential} */ public void managedIdentityCredentialsCodeSnippets() { TokenCredential managedIdentityCredentialUserAssigned = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); TokenCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link EnvironmentCredential} */ public void environmentCredentialsCodeSnippets() { TokenCredential environmentCredential = new EnvironmentCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AzureCliCredential} */ public void azureCliCredentialsCodeSnippets() { TokenCredential azureCliCredential = new AzureCliCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link IntelliJCredential} */ public void intelliJCredentialsCodeSnippets() { TokenCredential intelliJCredential = new IntelliJCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link DeviceCodeCredential} */ public void deviceCodeCredentialsCodeSnippets() { TokenCredential deviceCodeCredential = new DeviceCodeCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link UsernamePasswordCredential} */ public void usernamePasswordCredentialsCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId("<your app client ID>") .username("<your username>") .password("<your password>") .build(); } /** * Method to insert code snippets for {@link AzurePowerShellCredential} */ public void azurePowershellCredentialsCodeSnippets() { TokenCredential powerShellCredential = new AzurePowerShellCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AuthorizationCodeCredential} */
class JavaDocCodeSnippets { private String tenantId = System.getenv("AZURE_TENANT_ID"); private String clientId = System.getenv("AZURE_CLIENT_ID"); private String clientSecret = System.getenv("AZURE_CLIENT_SECRET"); private String serviceConnectionId = System.getenv("SERVICE_CONNECTION_ID"); private String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; private String fakePasswordPlaceholder = "fakePasswordPlaceholder"; /** * Method to insert code snippets for {@link ClientSecretCredential} */ public void clientSecretCredentialCodeSnippets() { TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build(); TokenCredential secretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientCertificateCredential} */ public void clientCertificateCredentialCodeSnippets() { TokenCredential clientCertificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate("<PATH-TO-PEM-CERTIFICATE>") .build(); byte[] certificateBytes = new byte[0]; ByteArrayInputStream certificateStream = new ByteArrayInputStream(certificateBytes); TokenCredential certificateCredentialWithStream = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificateStream) .build(); TokenCredential certificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pfxCertificate("<PATH-TO-PFX-CERTIFICATE>", "P@s$w0rd") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientAssertionCredential} */ public void clientAssertionCredentialCodeSnippets() { TokenCredential clientAssertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .build(); TokenCredential assertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ChainedTokenCredential} */ public void chainedTokenCredentialCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId(clientId) .username(fakeUsernamePlaceholder) .password(fakePasswordPlaceholder) .build(); TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .clientId(clientId) .port(8765) .build(); TokenCredential credential = new ChainedTokenCredentialBuilder() .addLast(usernamePasswordCredential) .addLast(interactiveBrowserCredential) .build(); } /** * Method to insert code snippets for {@link DefaultAzureCredential} */ public void defaultAzureCredentialCodeSnippets() { TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder() .build(); TokenCredential dacWithUserAssignedManagedIdentity = new DefaultAzureCredentialBuilder() .managedIdentityClientId("<Managed-Identity-Client-Id") .build(); } /** * Method to insert code snippets for {@link InteractiveBrowserCredential} */ public void interactiveBrowserCredentialsCodeSnippets() { TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .redirectUrl("http: .build(); } /** * Method to insert code snippets for {@link ManagedIdentityCredential} */ public void managedIdentityCredentialsCodeSnippets() { TokenCredential managedIdentityCredentialUserAssigned = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); TokenCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link EnvironmentCredential} */ public void environmentCredentialsCodeSnippets() { TokenCredential environmentCredential = new EnvironmentCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AzureCliCredential} */ public void azureCliCredentialsCodeSnippets() { TokenCredential azureCliCredential = new AzureCliCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link IntelliJCredential} */ public void intelliJCredentialsCodeSnippets() { TokenCredential intelliJCredential = new IntelliJCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link DeviceCodeCredential} */ public void deviceCodeCredentialsCodeSnippets() { TokenCredential deviceCodeCredential = new DeviceCodeCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link UsernamePasswordCredential} */ public void usernamePasswordCredentialsCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId("<your app client ID>") .username("<your username>") .password("<your password>") .build(); } /** * Method to insert code snippets for {@link AzurePowerShellCredential} */ public void azurePowershellCredentialsCodeSnippets() { TokenCredential powerShellCredential = new AzurePowerShellCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AuthorizationCodeCredential} */
nice catch!
public void shouldCancelWorkOnEmptyWindowTruncation() { final int windowSize = 50; final int cancelAfter = 0; final Duration windowTimeout = Duration.ofSeconds(20); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux().take(cancelAfter, false); StepVerifier.create(windowFlux).verifyComplete(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertTrue(work.isCanceled()); Assertions.assertFalse(work.hasTimedOut()); }
public void shouldCancelWorkOnEmptyWindowTruncation() { final int windowSize = 50; final int cancelAfter = 0; final Duration windowTimeout = Duration.ofSeconds(20); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux().take(cancelAfter, false); StepVerifier.create(windowFlux).verifyComplete(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertTrue(work.isCanceled()); Assertions.assertFalse(work.hasTimedOut()); }
class WindowedSubscriberFluxWindowTest { private static final HashMap<String, Object> EMPTY_LOGGING_CONTEXT = new HashMap<>(0); private static final String TERMINATED_MESSAGE = "client terminated"; @Test public void shouldCloseWindowForWorkArrivedAfterUpstreamError() { final int windowSize = 1; final Duration windowTimeout = Duration.ofSeconds(10); final RuntimeException upstreamError = new RuntimeException("connection-error"); final TestPublisher<Integer> upstream = TestPublisher.create(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); upstream.error(upstreamError); final EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux).verifyErrorSatisfies(e -> { final String message = e.getMessage(); Assertions.assertNotNull(message); assertUpstreamErrorMessage(message); Assertions.assertEquals(upstreamError, e.getCause()); }); upstream.assertNotCancelled(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertFalse(work.hasTimedOut()); Assertions.assertFalse(work.isCanceled()); } @Test public void shouldCloseStreamingWindowOnUpstreamError() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final RuntimeException upstreamError = new RuntimeException("connection-error"); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.error(upstreamError)) .expectNext(1, 2) .verifyErrorSatisfies(e0 -> { final String message0 = e0.getMessage(); Assertions.assertNotNull(message0); assertUpstreamErrorMessage(message0); Assertions.assertEquals(upstreamError, e0.getCause()); }); StepVerifier.create(window1Flux).expectNextCount(0).verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamErrorMessage(message1); Assertions.assertEquals(upstreamError, e1.getCause()); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCleanCloseStreamingWindowOnUpstreamError() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final RuntimeException upstreamError = new RuntimeException("connection-error"); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriberOptions<Integer> options = new WindowedSubscriberOptions<Integer>().cleanCloseStreamingWindowOnTerminate(); final WindowedSubscriber<Integer> subscriber = createSubscriber(options); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.error(upstreamError)) .expectNext(1, 2) .verifyComplete(); StepVerifier.create(window1Flux) .expectNextCount(0) .verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamErrorMessage(message1); Assertions.assertEquals(upstreamError, e1.getCause()); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCloseWindowForWorkArrivedAfterUpstreamCompletion() { final int windowSize = 1; final Duration windowTimeout = Duration.ofSeconds(10); final TestPublisher<Integer> upstream = TestPublisher.create(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); upstream.complete(); final EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux).verifyErrorSatisfies(e -> { final String message = e.getMessage(); Assertions.assertNotNull(message); assertUpstreamCompletedMessage(message); }); upstream.assertNotCancelled(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertFalse(work.hasTimedOut()); Assertions.assertFalse(work.isCanceled()); } @Test public void shouldCloseStreamingWindowOnUpstreamCompletion() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.complete()) .expectNext(1, 2) .verifyErrorSatisfies(e0 -> { final String message0 = e0.getMessage(); Assertions.assertNotNull(message0); assertUpstreamCompletedMessage(message0); }); StepVerifier.create(window1Flux).expectNextCount(0).verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamCompletedMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCleanCloseStreamingWindowOnUpstreamCompletion() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriberOptions<Integer> options = new WindowedSubscriberOptions<Integer>().cleanCloseStreamingWindowOnTerminate(); final WindowedSubscriber<Integer> subscriber = createSubscriber(options); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.complete()) .expectNext(1, 2) .verifyComplete(); StepVerifier.create(window1Flux) .expectNextCount(0) .verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamCompletedMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCloseWindowForWorkArrivedAfterDownstreamCancel() { final int windowSize = 1; final Duration windowTimeout = Duration.ofSeconds(10); final Flux<Integer> upstream = Flux.never(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribeWith(subscriber).cancel(); final EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux).verifyErrorSatisfies(e -> { final String message = e.getMessage(); Assertions.assertNotNull(message); assertDownstreamCanceledMessage(message); }); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertFalse(work.hasTimedOut()); Assertions.assertFalse(work.isCanceled()); } @Test public void shouldCloseStreamingWindowOnDownstreamCancel() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); final Disposable disposable = upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> disposable.dispose()) .expectNext(1, 2) .verifyErrorSatisfies(e0 -> { final String message0 = e0.getMessage(); Assertions.assertNotNull(message0); assertDownstreamCanceledMessage(message0); }); StepVerifier.create(window1Flux).expectNextCount(0).verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertDownstreamCanceledMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCleanCloseStreamingWindowOnDownstreamCancel() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriberOptions<Integer> options = new WindowedSubscriberOptions<Integer>().cleanCloseStreamingWindowOnTerminate(); final WindowedSubscriber<Integer> subscriber = createSubscriber(options); final Disposable disposable = upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> disposable.dispose()) .expectNext(1, 2) .verifyComplete(); StepVerifier.create(window1Flux) .expectNextCount(0) .verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertDownstreamCanceledMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCloseStreamingWindowOnceDemandReceived() { final int window0Size = 5; final int window1Size = 3; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(window0Size, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(window1Size, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.next(3)) .then(() -> upstream.next(4)) .then(() -> upstream.next(5)) .expectNext(1, 2, 3, 4, 5) .verifyComplete(); StepVerifier.create(window1Flux) .then(() -> upstream.next(6)) .then(() -> upstream.next(7)) .then(() -> upstream.next(8)) .expectNext(6, 7, 8) .verifyComplete(); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertEquals(0, work0.getPending()); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertEquals(0, work1.getPending()); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test @Test public void shouldCancelWorkOnStreamingWindowTruncation() { final int windowSize = 50; final int cancelAfter = 2; final Duration windowTimeout = Duration.ofSeconds(20); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux().take(cancelAfter); StepVerifier.create(windowFlux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.next(3)) .expectNext(1, 2) .verifyComplete(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertTrue(work.isCanceled()); Assertions.assertFalse(work.hasTimedOut()); } @Test public void shouldInvokeWindowDecorator() { final int windowSize = 2; final Duration windowTimeout = Duration.ofSeconds(20); final Decorator decorator = new Decorator(); final Upstream<String> upstream = new Upstream<>(); final WindowedSubscriberOptions<String> options = new WindowedSubscriberOptions<>(); final WindowedSubscriber<String> subscriber = createSubscriber(options.setWindowDecorator(decorator)); upstream.subscribe(subscriber); EnqueueResult<String> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<String> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux) .then(() -> upstream.next("A")) .then(() -> upstream.next("B")) .expectNext(Decorator.PREFIX + "A", Decorator.PREFIX + "B") .verifyComplete(); final WindowedSubscriber.WindowWork<String> work = r.getInnerWork(); Assertions.assertFalse(work.isCanceled()); Assertions.assertFalse(work.hasTimedOut()); } static void assertUpstreamErrorMessage(String message) { Assertions.assertTrue((TERMINATED_MESSAGE + " (Reason: upstream-error)").equals(message)); } static void assertUpstreamCompletedMessage(String message) { Assertions.assertTrue((TERMINATED_MESSAGE + " (Reason: upstream-completion)").equals(message)); } static void assertDownstreamCanceledMessage(String message) { Assertions.assertTrue((TERMINATED_MESSAGE + " (Reason: downstream-cancel)").equals(message)); } static WindowedSubscriber<Integer> createSubscriber() { return new WindowedSubscriber<>(EMPTY_LOGGING_CONTEXT, TERMINATED_MESSAGE, new WindowedSubscriberOptions<>()); } static <T> WindowedSubscriber<T> createSubscriber(WindowedSubscriberOptions<T> options) { return new WindowedSubscriber<>(EMPTY_LOGGING_CONTEXT, TERMINATED_MESSAGE, options); } static final class Upstream<T> { private final AtomicLong requested = new AtomicLong(0); private final Sinks.Many<T> sink = Sinks.many().multicast().onBackpressureBuffer(); Upstream() { } Disposable subscribe(WindowedSubscriber<T> subscriber) { return sink.asFlux().doOnRequest(r -> { requested.addAndGet(r); }).subscribeWith(subscriber); } long getRequested() { return requested.get(); } void next(T value) { if (requested.getAndDecrement() <= 0) { throw new IllegalStateException("No demand pending from WindowMessagesSubscriber."); } sink.emitNext(value, Sinks.EmitFailureHandler.FAIL_FAST); } void error(Throwable error) { sink.emitError(error, Sinks.EmitFailureHandler.FAIL_FAST); } void complete() { sink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST); } } static final class Decorator implements Function<Flux<String>, Flux<String>> { static final String PREFIX = "decorated-"; @Override public Flux<String> apply(Flux<String> toDecorate) { return toDecorate.map(v -> (PREFIX + v)); } } }
class WindowedSubscriberFluxWindowTest { private static final HashMap<String, Object> EMPTY_LOGGING_CONTEXT = new HashMap<>(0); private static final String TERMINATED_MESSAGE = "client terminated"; @Test public void shouldCloseWindowForWorkArrivedAfterUpstreamError() { final int windowSize = 1; final Duration windowTimeout = Duration.ofSeconds(10); final RuntimeException upstreamError = new RuntimeException("connection-error"); final TestPublisher<Integer> upstream = TestPublisher.create(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); upstream.error(upstreamError); final EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux).verifyErrorSatisfies(e -> { final String message = e.getMessage(); Assertions.assertNotNull(message); assertUpstreamErrorMessage(message); Assertions.assertEquals(upstreamError, e.getCause()); }); upstream.assertNotCancelled(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertFalse(work.hasTimedOut()); Assertions.assertFalse(work.isCanceled()); } @Test public void shouldCloseStreamingWindowOnUpstreamError() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final RuntimeException upstreamError = new RuntimeException("connection-error"); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.error(upstreamError)) .expectNext(1, 2) .verifyErrorSatisfies(e0 -> { final String message0 = e0.getMessage(); Assertions.assertNotNull(message0); assertUpstreamErrorMessage(message0); Assertions.assertEquals(upstreamError, e0.getCause()); }); StepVerifier.create(window1Flux).expectNextCount(0).verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamErrorMessage(message1); Assertions.assertEquals(upstreamError, e1.getCause()); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCleanCloseStreamingWindowOnUpstreamError() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final RuntimeException upstreamError = new RuntimeException("connection-error"); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriberOptions<Integer> options = new WindowedSubscriberOptions<Integer>().cleanCloseStreamingWindowOnTerminate(); final WindowedSubscriber<Integer> subscriber = createSubscriber(options); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.error(upstreamError)) .expectNext(1, 2) .verifyComplete(); StepVerifier.create(window1Flux) .expectNextCount(0) .verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamErrorMessage(message1); Assertions.assertEquals(upstreamError, e1.getCause()); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCloseWindowForWorkArrivedAfterUpstreamCompletion() { final int windowSize = 1; final Duration windowTimeout = Duration.ofSeconds(10); final TestPublisher<Integer> upstream = TestPublisher.create(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); upstream.complete(); final EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux).verifyErrorSatisfies(e -> { final String message = e.getMessage(); Assertions.assertNotNull(message); assertUpstreamCompletedMessage(message); }); upstream.assertNotCancelled(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertFalse(work.hasTimedOut()); Assertions.assertFalse(work.isCanceled()); } @Test public void shouldCloseStreamingWindowOnUpstreamCompletion() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.complete()) .expectNext(1, 2) .verifyErrorSatisfies(e0 -> { final String message0 = e0.getMessage(); Assertions.assertNotNull(message0); assertUpstreamCompletedMessage(message0); }); StepVerifier.create(window1Flux).expectNextCount(0).verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamCompletedMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCleanCloseStreamingWindowOnUpstreamCompletion() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriberOptions<Integer> options = new WindowedSubscriberOptions<Integer>().cleanCloseStreamingWindowOnTerminate(); final WindowedSubscriber<Integer> subscriber = createSubscriber(options); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.complete()) .expectNext(1, 2) .verifyComplete(); StepVerifier.create(window1Flux) .expectNextCount(0) .verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertUpstreamCompletedMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCloseWindowForWorkArrivedAfterDownstreamCancel() { final int windowSize = 1; final Duration windowTimeout = Duration.ofSeconds(10); final Flux<Integer> upstream = Flux.never(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribeWith(subscriber).cancel(); final EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux).verifyErrorSatisfies(e -> { final String message = e.getMessage(); Assertions.assertNotNull(message); assertDownstreamCanceledMessage(message); }); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertFalse(work.hasTimedOut()); Assertions.assertFalse(work.isCanceled()); } @Test public void shouldCloseStreamingWindowOnDownstreamCancel() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); final Disposable disposable = upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> disposable.dispose()) .expectNext(1, 2) .verifyErrorSatisfies(e0 -> { final String message0 = e0.getMessage(); Assertions.assertNotNull(message0); assertDownstreamCanceledMessage(message0); }); StepVerifier.create(window1Flux).expectNextCount(0).verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertDownstreamCanceledMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCleanCloseStreamingWindowOnDownstreamCancel() { final int windowSize = 10; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriberOptions<Integer> options = new WindowedSubscriberOptions<Integer>().cleanCloseStreamingWindowOnTerminate(); final WindowedSubscriber<Integer> subscriber = createSubscriber(options); final Disposable disposable = upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> disposable.dispose()) .expectNext(1, 2) .verifyComplete(); StepVerifier.create(window1Flux) .expectNextCount(0) .verifyErrorSatisfies(e1 -> { final String message1 = e1.getMessage(); Assertions.assertNotNull(message1); assertDownstreamCanceledMessage(message1); }); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test public void shouldCloseStreamingWindowOnceDemandReceived() { final int window0Size = 5; final int window1Size = 3; final Duration windowTimeout = Duration.ofSeconds(60); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); final EnqueueResult<Integer> r0 = subscriber.enqueueRequestImpl(window0Size, windowTimeout); final EnqueueResult<Integer> r1 = subscriber.enqueueRequestImpl(window1Size, windowTimeout); final Flux<Integer> window0Flux = r0.getWindowFlux(); final Flux<Integer> window1Flux = r1.getWindowFlux(); StepVerifier.create(window0Flux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.next(3)) .then(() -> upstream.next(4)) .then(() -> upstream.next(5)) .expectNext(1, 2, 3, 4, 5) .verifyComplete(); StepVerifier.create(window1Flux) .then(() -> upstream.next(6)) .then(() -> upstream.next(7)) .then(() -> upstream.next(8)) .expectNext(6, 7, 8) .verifyComplete(); final WindowedSubscriber.WindowWork<Integer> work0 = r0.getInnerWork(); Assertions.assertEquals(0, work0.getPending()); Assertions.assertFalse(work0.hasTimedOut()); Assertions.assertFalse(work0.isCanceled()); final WindowedSubscriber.WindowWork<Integer> work1 = r1.getInnerWork(); Assertions.assertEquals(0, work1.getPending()); Assertions.assertFalse(work1.hasTimedOut()); Assertions.assertFalse(work1.isCanceled()); } @Test @Test public void shouldCancelWorkOnStreamingWindowTruncation() { final int windowSize = 50; final int cancelAfter = 2; final Duration windowTimeout = Duration.ofSeconds(20); final Upstream<Integer> upstream = new Upstream<>(); final WindowedSubscriber<Integer> subscriber = createSubscriber(); upstream.subscribe(subscriber); EnqueueResult<Integer> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<Integer> windowFlux = r.getWindowFlux().take(cancelAfter); StepVerifier.create(windowFlux) .then(() -> upstream.next(1)) .then(() -> upstream.next(2)) .then(() -> upstream.next(3)) .expectNext(1, 2) .verifyComplete(); final WindowedSubscriber.WindowWork<Integer> work = r.getInnerWork(); Assertions.assertTrue(work.isCanceled()); Assertions.assertFalse(work.hasTimedOut()); } @Test public void shouldInvokeWindowDecorator() { final int windowSize = 2; final Duration windowTimeout = Duration.ofSeconds(20); final Decorator decorator = new Decorator(); final Upstream<String> upstream = new Upstream<>(); final WindowedSubscriberOptions<String> options = new WindowedSubscriberOptions<>(); final WindowedSubscriber<String> subscriber = createSubscriber(options.setWindowDecorator(decorator)); upstream.subscribe(subscriber); EnqueueResult<String> r = subscriber.enqueueRequestImpl(windowSize, windowTimeout); final Flux<String> windowFlux = r.getWindowFlux(); StepVerifier.create(windowFlux) .then(() -> upstream.next("A")) .then(() -> upstream.next("B")) .expectNext(Decorator.PREFIX + "A", Decorator.PREFIX + "B") .verifyComplete(); final WindowedSubscriber.WindowWork<String> work = r.getInnerWork(); Assertions.assertFalse(work.isCanceled()); Assertions.assertFalse(work.hasTimedOut()); } static void assertUpstreamErrorMessage(String message) { Assertions.assertTrue((TERMINATED_MESSAGE + " (Reason: upstream-error)").equals(message)); } static void assertUpstreamCompletedMessage(String message) { Assertions.assertTrue((TERMINATED_MESSAGE + " (Reason: upstream-completion)").equals(message)); } static void assertDownstreamCanceledMessage(String message) { Assertions.assertTrue((TERMINATED_MESSAGE + " (Reason: downstream-cancel)").equals(message)); } static WindowedSubscriber<Integer> createSubscriber() { return new WindowedSubscriber<>(EMPTY_LOGGING_CONTEXT, TERMINATED_MESSAGE, new WindowedSubscriberOptions<>()); } static <T> WindowedSubscriber<T> createSubscriber(WindowedSubscriberOptions<T> options) { return new WindowedSubscriber<>(EMPTY_LOGGING_CONTEXT, TERMINATED_MESSAGE, options); } static final class Upstream<T> { private final AtomicLong requested = new AtomicLong(0); private final Sinks.Many<T> sink = Sinks.many().multicast().onBackpressureBuffer(); Upstream() { } Disposable subscribe(WindowedSubscriber<T> subscriber) { return sink.asFlux().doOnRequest(r -> { requested.addAndGet(r); }).subscribeWith(subscriber); } long getRequested() { return requested.get(); } void next(T value) { if (requested.getAndDecrement() <= 0) { throw new IllegalStateException("No demand pending from WindowMessagesSubscriber."); } sink.emitNext(value, Sinks.EmitFailureHandler.FAIL_FAST); } void error(Throwable error) { sink.emitError(error, Sinks.EmitFailureHandler.FAIL_FAST); } void complete() { sink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST); } } static final class Decorator implements Function<Flux<String>, Flux<String>> { static final String PREFIX = "decorated-"; @Override public Flux<String> apply(Flux<String> toDecorate) { return toDecorate.map(v -> (PREFIX + v)); } } }
need to also close the clients after use - can happen in the close method
public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink connector"); this.sinkConfig = new CosmosSinkConfig(props); this.connectorName = props.containsKey(CONNECTOR_NAME) ? props.get(CONNECTOR_NAME).toString() : "EMPTY"; CosmosSinkContainersConfig containersConfig = this.sinkConfig.getContainersConfig(); CosmosAsyncClient cosmosAsyncClient = CosmosClientStore.getCosmosClient(this.sinkConfig.getAccountConfig(), this.connectorName); validateContainers(new ArrayList<>(containersConfig.getTopicToContainerMap().values()), cosmosAsyncClient, containersConfig.getDatabaseName()); }
CosmosAsyncClient cosmosAsyncClient = CosmosClientStore.getCosmosClient(this.sinkConfig.getAccountConfig(), this.connectorName);
public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink connector"); this.sinkConfig = new CosmosSinkConfig(props); this.connectorName = props.containsKey(CONNECTOR_NAME) ? props.get(CONNECTOR_NAME).toString() : "EMPTY"; CosmosSinkContainersConfig containersConfig = this.sinkConfig.getContainersConfig(); CosmosAsyncClient cosmosAsyncClient = CosmosClientStore.getCosmosClient(this.sinkConfig.getAccountConfig(), this.connectorName); validateContainers(new ArrayList<>(containersConfig.getTopicToContainerMap().values()), cosmosAsyncClient, containersConfig.getDatabaseName()); cosmosAsyncClient.close(); }
class CosmosSinkConnector extends SinkConnector { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkConnector.class); private static final String CONNECTOR_NAME = "name"; private CosmosSinkConfig sinkConfig; private String connectorName; @Override @Override public Class<? extends Task> taskClass() { return CosmosSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { LOGGER.info("Setting task configurations with maxTasks {}", maxTasks); List<Map<String, String>> configs = new ArrayList<>(); for (int i = 0; i < maxTasks; i++) { Map<String, String> taskConfigs = this.sinkConfig.originalsStrings(); taskConfigs.put(CosmosSinkTaskConfig.SINK_TASK_ID, String.format("%s-%s-%d", "sink", this.connectorName, RandomUtils.nextInt(1, 9999999))); configs.add(taskConfigs); } return configs; } @Override public void stop() { LOGGER.info("Kafka Cosmos sink connector {} is stopped."); } @Override public ConfigDef config() { return CosmosSinkConfig.getConfigDef(); } @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public Config validate(Map<String, String> connectorConfigs) { Config config = super.validate(connectorConfigs); if (config.configValues().stream().anyMatch(cv -> !cv.errorMessages().isEmpty())) { return config; } Map<String, ConfigValue> configValues = config .configValues() .stream() .collect(Collectors.toMap(ConfigValue::name, Function.identity())); validateCosmosAccountAuthConfig(configValues); validateThroughputControlConfig(configValues); validateWriteConfig(configValues); return config; } }
class CosmosSinkConnector extends SinkConnector { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkConnector.class); private static final String CONNECTOR_NAME = "name"; private CosmosSinkConfig sinkConfig; private String connectorName; @Override @Override public Class<? extends Task> taskClass() { return CosmosSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { LOGGER.info("Setting task configurations with maxTasks {}", maxTasks); List<Map<String, String>> configs = new ArrayList<>(); for (int i = 0; i < maxTasks; i++) { Map<String, String> taskConfigs = this.sinkConfig.originalsStrings(); taskConfigs.put(CosmosSinkTaskConfig.SINK_TASK_ID, String.format("%s-%s-%d", "sink", this.connectorName, RandomUtils.nextInt(1, 9999999))); configs.add(taskConfigs); } return configs; } @Override public void stop() { LOGGER.info("Kafka Cosmos sink connector {} is stopped."); } @Override public ConfigDef config() { return CosmosSinkConfig.getConfigDef(); } @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public Config validate(Map<String, String> connectorConfigs) { Config config = super.validate(connectorConfigs); if (config.configValues().stream().anyMatch(cv -> !cv.errorMessages().isEmpty())) { return config; } Map<String, ConfigValue> configValues = config .configValues() .stream() .collect(Collectors.toMap(ConfigValue::name, Function.identity())); validateCosmosAccountAuthConfig(configValues); validateThroughputControlConfig(configValues); validateWriteConfig(configValues); return config; } }
closed the client.
public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink connector"); this.sinkConfig = new CosmosSinkConfig(props); this.connectorName = props.containsKey(CONNECTOR_NAME) ? props.get(CONNECTOR_NAME).toString() : "EMPTY"; CosmosSinkContainersConfig containersConfig = this.sinkConfig.getContainersConfig(); CosmosAsyncClient cosmosAsyncClient = CosmosClientStore.getCosmosClient(this.sinkConfig.getAccountConfig(), this.connectorName); validateContainers(new ArrayList<>(containersConfig.getTopicToContainerMap().values()), cosmosAsyncClient, containersConfig.getDatabaseName()); }
CosmosAsyncClient cosmosAsyncClient = CosmosClientStore.getCosmosClient(this.sinkConfig.getAccountConfig(), this.connectorName);
public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink connector"); this.sinkConfig = new CosmosSinkConfig(props); this.connectorName = props.containsKey(CONNECTOR_NAME) ? props.get(CONNECTOR_NAME).toString() : "EMPTY"; CosmosSinkContainersConfig containersConfig = this.sinkConfig.getContainersConfig(); CosmosAsyncClient cosmosAsyncClient = CosmosClientStore.getCosmosClient(this.sinkConfig.getAccountConfig(), this.connectorName); validateContainers(new ArrayList<>(containersConfig.getTopicToContainerMap().values()), cosmosAsyncClient, containersConfig.getDatabaseName()); cosmosAsyncClient.close(); }
class CosmosSinkConnector extends SinkConnector { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkConnector.class); private static final String CONNECTOR_NAME = "name"; private CosmosSinkConfig sinkConfig; private String connectorName; @Override @Override public Class<? extends Task> taskClass() { return CosmosSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { LOGGER.info("Setting task configurations with maxTasks {}", maxTasks); List<Map<String, String>> configs = new ArrayList<>(); for (int i = 0; i < maxTasks; i++) { Map<String, String> taskConfigs = this.sinkConfig.originalsStrings(); taskConfigs.put(CosmosSinkTaskConfig.SINK_TASK_ID, String.format("%s-%s-%d", "sink", this.connectorName, RandomUtils.nextInt(1, 9999999))); configs.add(taskConfigs); } return configs; } @Override public void stop() { LOGGER.info("Kafka Cosmos sink connector {} is stopped."); } @Override public ConfigDef config() { return CosmosSinkConfig.getConfigDef(); } @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public Config validate(Map<String, String> connectorConfigs) { Config config = super.validate(connectorConfigs); if (config.configValues().stream().anyMatch(cv -> !cv.errorMessages().isEmpty())) { return config; } Map<String, ConfigValue> configValues = config .configValues() .stream() .collect(Collectors.toMap(ConfigValue::name, Function.identity())); validateCosmosAccountAuthConfig(configValues); validateThroughputControlConfig(configValues); validateWriteConfig(configValues); return config; } }
class CosmosSinkConnector extends SinkConnector { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkConnector.class); private static final String CONNECTOR_NAME = "name"; private CosmosSinkConfig sinkConfig; private String connectorName; @Override @Override public Class<? extends Task> taskClass() { return CosmosSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { LOGGER.info("Setting task configurations with maxTasks {}", maxTasks); List<Map<String, String>> configs = new ArrayList<>(); for (int i = 0; i < maxTasks; i++) { Map<String, String> taskConfigs = this.sinkConfig.originalsStrings(); taskConfigs.put(CosmosSinkTaskConfig.SINK_TASK_ID, String.format("%s-%s-%d", "sink", this.connectorName, RandomUtils.nextInt(1, 9999999))); configs.add(taskConfigs); } return configs; } @Override public void stop() { LOGGER.info("Kafka Cosmos sink connector {} is stopped."); } @Override public ConfigDef config() { return CosmosSinkConfig.getConfigDef(); } @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public Config validate(Map<String, String> connectorConfigs) { Config config = super.validate(connectorConfigs); if (config.configValues().stream().anyMatch(cv -> !cv.errorMessages().isEmpty())) { return config; } Map<String, ConfigValue> configValues = config .configValues() .stream() .collect(Collectors.toMap(ConfigValue::name, Function.identity())); validateCosmosAccountAuthConfig(configValues); validateThroughputControlConfig(configValues); validateWriteConfig(configValues); return config; } }
Remove it also from `EncryptedBlobClientBuilder endpoint(String endpoint)` https://github.com/Azure/azure-sdk-for-java/blob/5f96f6ab2124bb45095670866fb89ff850074cad/sdk/storage/azure-storage-blob-cryptography/src/main/java/com/azure/storage/blob/specialized/cryptography/EncryptedBlobClientBuilder.java#L562
public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Objects.requireNonNull(blobName, "'blobName' cannot be null."); return this; }
this.blobName = Objects.requireNonNull(blobName, "'blobName' cannot be null.");
public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Objects.requireNonNull(blobName, "'blobName' cannot be null."); return this; }
class EncryptedBlobClientBuilder implements TokenCredentialTrait<EncryptedBlobClientBuilder>, ConnectionStringTrait<EncryptedBlobClientBuilder>, AzureNamedKeyCredentialTrait<EncryptedBlobClientBuilder>, AzureSasCredentialTrait<EncryptedBlobClientBuilder>, HttpTrait<EncryptedBlobClientBuilder>, ConfigurationTrait<EncryptedBlobClientBuilder>, EndpointTrait<EncryptedBlobClientBuilder> { private static final ClientLogger LOGGER = new ClientLogger(EncryptedBlobClientBuilder.class); private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-storage-blob-cryptography.properties"); private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String BLOB_CLIENT_NAME = USER_AGENT_PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String BLOB_CLIENT_VERSION = USER_AGENT_PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String USER_AGENT_MODIFICATION_REGEX = "(.*? )?(azsdk-java-azure-storage-blob/12\\.\\d{1,2}\\.\\d{1,2}(?:-beta\\.\\d{1,2})?)( .*?)?"; private String endpoint; private String accountName; private String containerName; private String blobName; private String snapshot; private String versionId; private boolean requiresEncryption; private final EncryptionVersion encryptionVersion; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; private BlobServiceVersion version; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; /** * Creates a new instance of the EncryptedBlobClientBuilder * @deprecated Use {@link EncryptedBlobClientBuilder */ @Deprecated public EncryptedBlobClientBuilder() { logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = EncryptionVersion.V1; LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } /** * Creates a new instance of the EncryptedBlobClientbuilder. * * @param version The version of the client side encryption protocol to use. It is highly recommended that v2 be * preferred for security reasons, though v1 continues to be supported for compatibility reasons. Note that even a * client configured to encrypt using v2 can decrypt blobs that use the v1 protocol. */ public EncryptedBlobClientBuilder(EncryptionVersion version) { Objects.requireNonNull(version); logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = version; if (EncryptionVersion.V1.equals(this.encryptionVersion)) { LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * <pre> * EncryptedBlobAsyncClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobAsyncClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * <pre> * EncryptedBlobClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); checkValidEncryptionParameters(); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); return new EncryptedBlobAsyncClient(addBlobUserAgentModificationPolicy(getHttpPipeline()), endpoint, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, keyWrapper, keyWrapAlgorithm, versionId, encryptionVersion, requiresEncryption); } private HttpPipeline addBlobUserAgentModificationPolicy(HttpPipeline pipeline) { List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = pipeline.getPolicy(i); policies.add(currPolicy); if (currPolicy instanceof UserAgentPolicy) { policies.add(new BlobUserAgentModificationPolicy(CLIENT_NAME, CLIENT_VERSION)); } } return new HttpPipelineBuilder() .httpClient(pipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .tracer(pipeline.getTracer()) .build(); } private String modifyUserAgentString(String applicationId, Configuration userAgentConfiguration) { Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX); String userAgent = UserAgentUtil.toUserAgentString(applicationId, BLOB_CLIENT_NAME, BLOB_CLIENT_VERSION, userAgentConfiguration); Matcher matcher = pattern.matcher(userAgent); String version = encryptionVersion == EncryptionVersion.V2 ? "2.0" : "1.0"; String stringToAppend = "azstorage-clientsideencryption/" + version; if (matcher.matches() && !userAgent.contains(stringToAppend)) { String segment1 = matcher.group(1) == null ? "" : matcher.group(1); String segment2 = matcher.group(2) == null ? "" : matcher.group(2); String segment3 = matcher.group(3) == null ? "" : matcher.group(3); userAgent = segment1 + stringToAppend + " " + segment2 + segment3; } return userAgent; } private HttpPipeline getHttpPipeline() { CredentialValidator.validateSingleCredentialIsPresent( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, LOGGER); if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); if (currPolicy instanceof BlobDecryptionPolicy) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The passed pipeline was already" + " configured for encryption/decryption in a way that might conflict with the passed key " + "information. Please ensure that the passed pipeline is not already configured for " + "encryption/decryption")); } policies.add(currPolicy); } policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); return new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .tracer(httpPipeline.getTracer()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId() : logOptions.getApplicationId(); String modifiedUserAgent = modifyUserAgentString(applicationId, userAgentConfiguration); policies.add(new UserAgentPolicy(modifiedUserAgent)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, LOGGER)); policies.add(new AddDatePolicy()); HttpHeaders headers = new HttpHeaders(); clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new MetadataValidationPolicy()); if (storageSharedKeyCredential != null) { policies.add(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)); } else if (tokenCredential != null) { BuilderHelper.httpsValidation(tokenCredential, "bearer token", endpoint, LOGGER); policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE)); } else if (azureSasCredential != null) { policies.add(new AzureSasCredentialPolicy(azureSasCredential, false)); } else if (sasToken != null) { policies.add(new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false)); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new ResponseValidationPolicyBuilder() .addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID) .addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256) .build()); policies.add(new HttpLoggingPolicy(logOptions)); policies.add(new ScrubEtagPolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(createTracer(clientOptions)) .build(); } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key.")); } } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public EncryptedBlobClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * 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 EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public EncryptedBlobClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Clears the credential used to authorize the request. * * <p>This is for blobs that are publicly accessible.</p> * * @return the updated EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder setAnonymousAccess() { this.storageSharedKeyCredential = null; this.tokenCredential = null; this.azureSasCredential = null; this.sasToken = null; return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated EncryptedBlobClientBuilder * @throws IllegalArgumentException If {@code connectionString} is invalid. */ @Override public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, LOGGER); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw LOGGER .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * * <p>If the blob name contains special characters, pass in the url encoded version of the blob name. </p> * * <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name * as the container name. With only one path element, it is impossible to distinguish between a container name and a * blob in the root container, so it is assumed to be the container name as this is much more common. When working * with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name * separately using the {@link EncryptedBlobClientBuilder * * @param endpoint URL of the service * @return the updated EncryptedBlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); this.containerName = parts.getBlobContainerName() == null ? this.containerName : parts.getBlobContainerName(); this.blobName = parts.getBlobName() == null ? this.blobName : Utility.urlEncode(parts.getBlobName()); this.snapshot = parts.getSnapshot(); this.versionId = parts.getVersionId(); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex)); } return this; } /** * Sets the name of the container that contains the blob. * * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root}, * will be used. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob. * * @param blobName Name of the blob. If the blob name contains special characters, pass in the url encoded version * of the blob name. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ /** * Sets the snapshot identifier of the blob. * * @param snapshot Snapshot identifier for the blob. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the version identifier of the blob. * * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder versionId(String versionId) { this.versionId = versionId; 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 httpClient The {@link HttpClient} to use for requests. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { LOGGER.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; 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 pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } 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 EncryptedBlobClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated EncryptedBlobClientBuilder object. */ public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; 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 * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; 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 * {@link * not ignored when {@code pipeline} is set. * * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; 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 EncryptedBlobClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link BlobServiceVersion} 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 of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey {@link CustomerProvidedKey} * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobClient BlobClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobClient(BlobClient blobClient) { Objects.requireNonNull(blobClient); return client(blobClient.getHttpPipeline(), blobClient.getBlobUrl(), blobClient.getServiceVersion()); } /** * Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobAsyncClient BlobAsyncClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobAsyncClient(BlobAsyncClient blobAsyncClient) { Objects.requireNonNull(blobAsyncClient); return client(blobAsyncClient.getHttpPipeline(), blobAsyncClient.getBlobUrl(), blobAsyncClient.getServiceVersion()); } /** * Helper method to transform a regular client into an encrypted client * * @param httpPipeline {@link HttpPipeline} * @param endpoint The endpoint. * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ private EncryptedBlobClientBuilder client(HttpPipeline httpPipeline, String endpoint, BlobServiceVersion version) { this.endpoint(endpoint); this.serviceVersion(version); return this.pipeline(httpPipeline); } /** * Sets the requires encryption option. * * @param requiresEncryption Whether encryption is enforced by this client. Client will throw if data is * downloaded and it is not encrypted. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder requiresEncryption(boolean requiresEncryption) { this.requiresEncryption = requiresEncryption; return this; } }
class EncryptedBlobClientBuilder implements TokenCredentialTrait<EncryptedBlobClientBuilder>, ConnectionStringTrait<EncryptedBlobClientBuilder>, AzureNamedKeyCredentialTrait<EncryptedBlobClientBuilder>, AzureSasCredentialTrait<EncryptedBlobClientBuilder>, HttpTrait<EncryptedBlobClientBuilder>, ConfigurationTrait<EncryptedBlobClientBuilder>, EndpointTrait<EncryptedBlobClientBuilder> { private static final ClientLogger LOGGER = new ClientLogger(EncryptedBlobClientBuilder.class); private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-storage-blob-cryptography.properties"); private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String BLOB_CLIENT_NAME = USER_AGENT_PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); private static final String BLOB_CLIENT_VERSION = USER_AGENT_PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); private static final String USER_AGENT_MODIFICATION_REGEX = "(.*? )?(azsdk-java-azure-storage-blob/12\\.\\d{1,2}\\.\\d{1,2}(?:-beta\\.\\d{1,2})?)( .*?)?"; private String endpoint; private String accountName; private String containerName; private String blobName; private String snapshot; private String versionId; private boolean requiresEncryption; private final EncryptionVersion encryptionVersion; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; private BlobServiceVersion version; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; /** * Creates a new instance of the EncryptedBlobClientBuilder * @deprecated Use {@link EncryptedBlobClientBuilder */ @Deprecated public EncryptedBlobClientBuilder() { logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = EncryptionVersion.V1; LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } /** * Creates a new instance of the EncryptedBlobClientbuilder. * * @param version The version of the client side encryption protocol to use. It is highly recommended that v2 be * preferred for security reasons, though v1 continues to be supported for compatibility reasons. Note that even a * client configured to encrypt using v2 can decrypt blobs that use the v1 protocol. */ public EncryptedBlobClientBuilder(EncryptionVersion version) { Objects.requireNonNull(version); logOptions = getDefaultHttpLogOptions(); this.encryptionVersion = version; if (EncryptionVersion.V1.equals(this.encryptionVersion)) { LOGGER.warning("Client is being configured to use v1 of client side encryption, " + "which is no longer considered secure. The default is v1 for compatibility reasons, but it is highly" + "recommended the version be set to v2 using the constructor"); } } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * <pre> * EncryptedBlobAsyncClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobAsyncClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient --> * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * <pre> * EncryptedBlobClient client = new EncryptedBlobClientBuilder& * .key& * .keyResolver& * .connectionString& * .containerName& * .blobName& * .buildEncryptedBlobClient& * </pre> * <!-- end com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient --> * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); checkValidEncryptionParameters(); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (CoreUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); return new EncryptedBlobAsyncClient(addBlobUserAgentModificationPolicy(getHttpPipeline()), endpoint, serviceVersion, accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, keyWrapper, keyWrapAlgorithm, versionId, encryptionVersion, requiresEncryption); } private HttpPipeline addBlobUserAgentModificationPolicy(HttpPipeline pipeline) { List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = pipeline.getPolicy(i); policies.add(currPolicy); if (currPolicy instanceof UserAgentPolicy) { policies.add(new BlobUserAgentModificationPolicy(CLIENT_NAME, CLIENT_VERSION)); } } return new HttpPipelineBuilder() .httpClient(pipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .tracer(pipeline.getTracer()) .build(); } private String modifyUserAgentString(String applicationId, Configuration userAgentConfiguration) { Pattern pattern = Pattern.compile(USER_AGENT_MODIFICATION_REGEX); String userAgent = UserAgentUtil.toUserAgentString(applicationId, BLOB_CLIENT_NAME, BLOB_CLIENT_VERSION, userAgentConfiguration); Matcher matcher = pattern.matcher(userAgent); String version = encryptionVersion == EncryptionVersion.V2 ? "2.0" : "1.0"; String stringToAppend = "azstorage-clientsideencryption/" + version; if (matcher.matches() && !userAgent.contains(stringToAppend)) { String segment1 = matcher.group(1) == null ? "" : matcher.group(1); String segment2 = matcher.group(2) == null ? "" : matcher.group(2); String segment3 = matcher.group(3) == null ? "" : matcher.group(3); userAgent = segment1 + stringToAppend + " " + segment2 + segment3; } return userAgent; } private HttpPipeline getHttpPipeline() { CredentialValidator.validateSingleCredentialIsPresent( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, LOGGER); if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); if (currPolicy instanceof BlobDecryptionPolicy) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("The passed pipeline was already" + " configured for encryption/decryption in a way that might conflict with the passed key " + "information. Please ensure that the passed pipeline is not already configured for " + "encryption/decryption")); } policies.add(currPolicy); } policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); return new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .tracer(httpPipeline.getTracer()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } Configuration userAgentConfiguration = (configuration == null) ? Configuration.NONE : configuration; List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver, requiresEncryption)); String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId() : logOptions.getApplicationId(); String modifiedUserAgent = modifyUserAgentString(applicationId, userAgentConfiguration); policies.add(new UserAgentPolicy(modifiedUserAgent)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, LOGGER)); policies.add(new AddDatePolicy()); HttpHeaders headers = new HttpHeaders(); clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new MetadataValidationPolicy()); if (storageSharedKeyCredential != null) { policies.add(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)); } else if (tokenCredential != null) { BuilderHelper.httpsValidation(tokenCredential, "bearer token", endpoint, LOGGER); policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE)); } else if (azureSasCredential != null) { policies.add(new AzureSasCredentialPolicy(azureSasCredential, false)); } else if (sasToken != null) { policies.add(new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false)); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new ResponseValidationPolicyBuilder() .addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID) .addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256) .build()); policies.add(new HttpLoggingPolicy(logOptions)); policies.add(new ScrubEtagPolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(createTracer(clientOptions)) .build(); } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Key Wrap Algorithm must be specified with a Key.")); } } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public EncryptedBlobClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * 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 EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public EncryptedBlobClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated EncryptedBlobClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public EncryptedBlobClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Clears the credential used to authorize the request. * * <p>This is for blobs that are publicly accessible.</p> * * @return the updated EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder setAnonymousAccess() { this.storageSharedKeyCredential = null; this.tokenCredential = null; this.azureSasCredential = null; this.sasToken = null; return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated EncryptedBlobClientBuilder * @throws IllegalArgumentException If {@code connectionString} is invalid. */ @Override public EncryptedBlobClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, LOGGER); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw LOGGER .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * * <p>If the endpoint is to a blob in the root container, this method will fail as it will interpret the blob name * as the container name. With only one path element, it is impossible to distinguish between a container name and a * blob in the root container, so it is assumed to be the container name as this is much more common. When working * with blobs in the root container, it is best to set the endpoint to the account url and specify the blob name * separately using the {@link EncryptedBlobClientBuilder * * @param endpoint URL of the service * @return the updated EncryptedBlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); this.containerName = parts.getBlobContainerName() == null ? this.containerName : parts.getBlobContainerName(); this.blobName = parts.getBlobName() == null ? this.blobName : parts.getBlobName(); this.snapshot = parts.getSnapshot(); this.versionId = parts.getVersionId(); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex)); } return this; } /** * Sets the name of the container that contains the blob. * * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root}, * will be used. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob. * * @param blobName Name of the blob. If the blob name contains special characters, pass in the url encoded version * of the blob name. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ /** * Sets the snapshot identifier of the blob. * * @param snapshot Snapshot identifier for the blob. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the version identifier of the blob. * * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder versionId(String versionId) { this.versionId = versionId; 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 httpClient The {@link HttpClient} to use for requests. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { LOGGER.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; 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 pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public EncryptedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } 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 EncryptedBlobClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated EncryptedBlobClientBuilder object. */ public EncryptedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; 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 * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; 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 * {@link * not ignored when {@code pipeline} is set. * * @return the updated EncryptedBlobClientBuilder object */ @Override public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; 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 EncryptedBlobClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public EncryptedBlobClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link BlobServiceVersion} 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 of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey {@link CustomerProvidedKey} * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobClient BlobClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobClient(BlobClient blobClient) { Objects.requireNonNull(blobClient); return client(blobClient.getHttpPipeline(), blobClient.getBlobUrl(), blobClient.getServiceVersion()); } /** * Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline}, * {@link URL} and {@link BlobServiceVersion} that are used to interact with the service. Note that the underlying * pipeline should not already be configured for encryption/decryption. * * <p>If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * <p>Note that for security reasons, this method does not copy over the {@link CustomerProvidedKey} and * encryption scope properties from the provided client. To set CPK, please use * {@link * * @param blobAsyncClient BlobAsyncClient used to configure the builder. * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code containerClient} is {@code null}. */ public EncryptedBlobClientBuilder blobAsyncClient(BlobAsyncClient blobAsyncClient) { Objects.requireNonNull(blobAsyncClient); return client(blobAsyncClient.getHttpPipeline(), blobAsyncClient.getBlobUrl(), blobAsyncClient.getServiceVersion()); } /** * Helper method to transform a regular client into an encrypted client * * @param httpPipeline {@link HttpPipeline} * @param endpoint The endpoint. * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated EncryptedBlobClientBuilder object */ private EncryptedBlobClientBuilder client(HttpPipeline httpPipeline, String endpoint, BlobServiceVersion version) { this.endpoint(endpoint); this.serviceVersion(version); return this.pipeline(httpPipeline); } /** * Sets the requires encryption option. * * @param requiresEncryption Whether encryption is enforced by this client. Client will throw if data is * downloaded and it is not encrypted. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder requiresEncryption(boolean requiresEncryption) { this.requiresEncryption = requiresEncryption; return this; } }
Add changelog
public void metricConfigsThroughSystemProperty() { System.setProperty( "COSMOS.METRICS_CONFIG", "{\"metricCategories\":\"[OperationDetails]\"," + "\"tagNames\":\"[PartitionId]\"," + "\"sampleRate\":0.5," + "\"percentiles\":[0.90,0.99]," + "\"enableHistograms\":false," + "\"applyDiagnosticThresholdsForTransportLevelMeters\":true}"); CosmosClientBuilder testClientBuilder = new CosmosClientBuilder(); CosmosClientTelemetryConfig clientTelemetryConfig = ReflectionUtils.getClientTelemetryConfig(testClientBuilder); EnumSet<MetricCategory> effectiveMetricsCategory = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getMetricCategories(clientTelemetryConfig); assertThat(effectiveMetricsCategory).containsAll(MetricCategory.MINIMAL_CATEGORIES); assertThat(effectiveMetricsCategory).contains(MetricCategory.OperationDetails); EnumSet<TagName> effectiveTagNames = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getMetricTagNames(clientTelemetryConfig); assertThat(effectiveTagNames).containsAll(TagName.MINIMUM_TAGS); assertThat(effectiveTagNames).contains(TagName.PartitionId); double sampleRate = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getSamplingRate(clientTelemetryConfig); assertThat(sampleRate).isEqualTo(0.5); double[] percentiles = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getDefaultPercentiles(clientTelemetryConfig); assertThat(percentiles).contains(0.90, 0.99); boolean publishHistograms = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .shouldPublishHistograms(clientTelemetryConfig); assertThat(publishHistograms).isFalse(); boolean applyDiagnosticThresholdsForTransportLevelMeters = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .shouldApplyDiagnosticThresholdsForTransportLevelMeters(clientTelemetryConfig); assertThat(applyDiagnosticThresholdsForTransportLevelMeters).isTrue(); System.clearProperty("COSMOS.METRICS_CONFIG"); }
.getCosmosClientTelemetryConfigAccessor()
public void metricConfigsThroughSystemProperty() { System.setProperty( "COSMOS.METRICS_CONFIG", "{\"metricCategories\":\"[OperationDetails]\"," + "\"tagNames\":\"[PartitionId]\"," + "\"sampleRate\":0.5," + "\"percentiles\":[0.90,0.99]," + "\"enableHistograms\":false," + "\"applyDiagnosticThresholdsForTransportLevelMeters\":true}"); CosmosClientBuilder testClientBuilder = new CosmosClientBuilder(); CosmosClientTelemetryConfig clientTelemetryConfig = ReflectionUtils.getClientTelemetryConfig(testClientBuilder); EnumSet<MetricCategory> effectiveMetricsCategory = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getMetricCategories(clientTelemetryConfig); assertThat(effectiveMetricsCategory).containsAll(MetricCategory.MINIMAL_CATEGORIES); assertThat(effectiveMetricsCategory).contains(MetricCategory.OperationDetails); EnumSet<TagName> effectiveTagNames = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getMetricTagNames(clientTelemetryConfig); assertThat(effectiveTagNames).containsAll(TagName.MINIMUM_TAGS); assertThat(effectiveTagNames).contains(TagName.PartitionId); double sampleRate = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getSamplingRate(clientTelemetryConfig); assertThat(sampleRate).isEqualTo(0.5); double[] percentiles = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getDefaultPercentiles(clientTelemetryConfig); assertThat(percentiles).contains(0.90, 0.99); boolean publishHistograms = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .shouldPublishHistograms(clientTelemetryConfig); assertThat(publishHistograms).isFalse(); boolean applyDiagnosticThresholdsForTransportLevelMeters = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .shouldApplyDiagnosticThresholdsForTransportLevelMeters(clientTelemetryConfig); assertThat(applyDiagnosticThresholdsForTransportLevelMeters).isTrue(); System.clearProperty("COSMOS.METRICS_CONFIG"); }
class ClientMetricsTest extends BatchTestBase { private CosmosClient client; private CosmosContainer container; private String databaseId; private String containerId; private MeterRegistry meterRegistry; private String preferredRegion; private CosmosClientTelemetryConfig inputClientTelemetryConfig; private CosmosMicrometerMetricsOptions inputMetricsOptions; private Tag clientCorrelationTag; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public ClientMetricsTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } private EnumSet<MetricCategory> getEffectiveMetricCategories() { return ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getMetricCategories(this.inputClientTelemetryConfig); } public void beforeTest(CosmosMetricCategory... metricCategories) { beforeTest(null, metricCategories); } public void beforeTest( CosmosDiagnosticsThresholds thresholds, CosmosMetricCategory... metricCategories) { assertThat(this.client).isNull(); assertThat(this.meterRegistry).isNull(); this.meterRegistry = ConsoleLoggingRegistryFactory.create(1); this.inputMetricsOptions = new CosmosMicrometerMetricsOptions() .meterRegistry(this.meterRegistry) .setMetricCategories(metricCategories) .configureDefaultTagNames( CosmosMetricTagName.DEFAULT, CosmosMetricTagName.PARTITION_ID, CosmosMetricTagName.REPLICA_ID, CosmosMetricTagName.OPERATION_SUB_STATUS_CODE, CosmosMetricTagName.PARTITION_KEY_RANGE_ID); this.inputClientTelemetryConfig = new CosmosClientTelemetryConfig() .metricsOptions(this.inputMetricsOptions); if (thresholds != null) { this.inputClientTelemetryConfig.diagnosticsThresholds(thresholds); this.inputMetricsOptions.applyDiagnosticThresholdsForTransportLevelMeters(true); } this.client = getClientBuilder() .clientTelemetryConfig(inputClientTelemetryConfig) .buildClient(); assertThat( ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(this.client.asyncClient()) ).isSameAs(this.getEffectiveMetricCategories()); AsyncDocumentClient asyncDocumentClient = ReflectionUtils.getAsyncDocumentClient(this.client.asyncClient()); RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) asyncDocumentClient; List<String> writeRegions = this.getAvailableWriteRegionNames(rxDocumentClient); assertThat(writeRegions).isNotNull().isNotEmpty(); this.preferredRegion = writeRegions.iterator().next(); if (databaseId == null) { CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); this.databaseId = asyncContainer.getDatabase().getId(); this.containerId = asyncContainer.getId(); } this.clientCorrelationTag = client.asyncClient().getClientCorrelationTag(); container = client.getDatabase(databaseId).getContainer(containerId); } public void afterTest() { this.container = null; CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { this.client.close(); } this.client = null; MeterRegistry meterRegistrySnapshot = this.meterRegistry; if (meterRegistrySnapshot != null) { meterRegistrySnapshot.clear(); meterRegistrySnapshot.close(); } this.meterRegistry = null; } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void maxValueExceedingDefinedLimitStillWorksWithoutException() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { Tag dummyOperationTag = Tag.of(TagName.Operation.toString(), "TestDummy"); Timer latencyMeter = Timer .builder("cosmos.client.op.latency") .description("Operation latency") .maximumExpectedValue(Duration.ofSeconds(300)) .publishPercentiles(0.95, 0.99) .publishPercentileHistogram(true) .tags(Collections.singleton(dummyOperationTag)) .register(this.meterRegistry); latencyMeter.record(Duration.ofSeconds(600)); Meter requestLatencyMeter = this.assertMetrics( "cosmos.client.op.latency", true, dummyOperationTag); List<Measurement> measurements = new ArrayList<>(); requestLatencyMeter.measure().forEach(measurements::add); int expectedMeasurementCount = 3; if (measurements.size() < expectedMeasurementCount) { logger.error("Size should have been 3 but was {}", measurements.size()); for (int i = 0; i < measurements.size(); i++) { Measurement m = measurements.get(i); logger.error( "{}: {}", i, m); } } assertThat(measurements.size()).isGreaterThanOrEqualTo(expectedMeasurementCount); assertThat(measurements.get(0).getStatistic().getTagValueRepresentation()).isEqualTo("count"); assertThat(measurements.get(0).getValue()).isEqualTo(1); assertThat(measurements.get(1).getStatistic().getTagValueRepresentation()).isEqualTo("total"); assertThat(measurements.get(1).getValue()).isEqualTo(600 * 1000); assertThat(measurements.get(2).getStatistic().getTagValueRepresentation()).isEqualTo("max"); assertThat(measurements.get(2).getValue()).isEqualTo(600 * 1000); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void createItem() throws Exception { boolean[] disableLatencyMeterTestCases = { false, true }; for (boolean disableLatencyMeter: disableLatencyMeterTestCases) { this.beforeTest(CosmosMetricCategory.DEFAULT); if (disableLatencyMeter) { this.inputMetricsOptions .configureMeter( CosmosMetricName.fromString(CosmosMetricName.OPERATION_SUMMARY_LATENCY.toString().toUpperCase(Locale.ROOT)), new CosmosMicrometerMeterOptions().setEnabled(false)); } try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); Tag expectedOperationTag = Tag.of(TagName.OperationStatusCode.toString(), "201"); this.assertMetrics("cosmos.client.op.latency", !disableLatencyMeter, expectedOperationTag); Tag expectedSubStatusCodeOperationTag = Tag.of(TagName.OperationSubStatusCode.toString(), "0"); this.assertMetrics("cosmos.client.op.latency", !disableLatencyMeter, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedOperationTag); if (!disableLatencyMeter) { Tag expectedRequestTag = Tag.of(TagName.RequestStatusCode.toString(), "201/0"); this.validateMetrics( expectedOperationTag, expectedRequestTag, 0, 300 ); if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() == ConnectionMode.DIRECT) { Meter foundMeter = this.assertMetrics( "cosmos.client.req.rntbd.latency", true, expectedRequestTag); assertThat(foundMeter).isNotNull(); boolean replicaIdDimensionExists = foundMeter .getId() .getTags() .stream() .anyMatch(tag -> tag.getKey().equals(TagName.ReplicaId.toString()) && !tag.getValue().equals("NONE")); assertThat(replicaIdDimensionExists) .isEqualTo(true); } this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Create"), Tag.of(TagName.RequestOperationType.toString(), "Document/Create"), 0, 300 ); } } finally { this.afterTest(); } } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void createItemWithAllMetrics() throws Exception { boolean[] suppressConsistencyLevelTagTestCases = { false, true }; for (boolean suppressConsistencyLevelTag: suppressConsistencyLevelTagTestCases) { this.beforeTest(CosmosMetricCategory.ALL); this .inputMetricsOptions .configureDefaultTagNames(CosmosMetricTagName.ALL); if (suppressConsistencyLevelTag) { this .inputMetricsOptions .configureMeter( CosmosMetricName.OPERATION_SUMMARY_LATENCY, new CosmosMicrometerMeterOptions() .suppressTagNames(CosmosMetricTagName.fromString("ConsistencyLevel")) .enableHistograms(false) .configurePercentiles(0.99, 0.999)); } try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "201"), Tag.of(TagName.RequestStatusCode.toString(), "201/0"), 0, 300 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Create"), Tag.of(TagName.RequestOperationType.toString(), "Document/Create"), 0, 300 ); String expectedConsistencyLevel = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getEffectiveConsistencyLevel( client.asyncClient(), OperationType.Create, null) .toString(); Tag expectedConsistencyTag = Tag.of(TagName.ConsistencyLevel.toString(), expectedConsistencyLevel); this.assertMetrics( "cosmos.client.op.latency", !suppressConsistencyLevelTag, expectedConsistencyTag); this.assertMetrics( "cosmos.client.op.calls", true, expectedConsistencyTag); } finally { this.afterTest(); } } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosItemResponse<InternalObjectNode> readResponse1 = container.readItem(properties.getId(), new PartitionKey(properties.get("mypk")), new CosmosItemRequestOptions(), InternalObjectNode.class); validateItemResponse(properties, readResponse1); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 500 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Read"), Tag.of(TagName.RequestOperationType.toString(), "Document/Read"), 0, 500 ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readManySingleItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); List<CosmosItemIdentity> tuplesToBeRead = new ArrayList<>(); tuplesToBeRead.add(new CosmosItemIdentity( new PartitionKey(properties.get("mypk")), properties.getId() )); FeedResponse<InternalObjectNode> readManyResponse = container.readMany( tuplesToBeRead, new CosmosReadManyRequestOptions(), InternalObjectNode.class); validateReadManyFeedResponse(Arrays.asList(properties), readManyResponse); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 500 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/readMany"), Tag.of(TagName.RequestOperationType.toString(), "Document/Read"), 0, 500 ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readManyMultipleItems() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); List<InternalObjectNode> createdDocs = new ArrayList<>(); List<CosmosItemIdentity> tuplesToBeRead = new ArrayList<>(); try { for (int i = 0; i < 20; i++) { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); createdDocs.add(properties); tuplesToBeRead.add(new CosmosItemIdentity( new PartitionKey(properties.get("mypk")), properties.getId() )); } FeedResponse<InternalObjectNode> readManyResponse = container.readMany( tuplesToBeRead, new CosmosReadManyRequestOptions(), InternalObjectNode.class); validateReadManyFeedResponse(createdDocs, readManyResponse); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 500 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/readMany"), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 500 ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } private void runReadItemTestWithThresholds( CosmosDiagnosticsThresholds thresholds, boolean expectRequestMetrics ) { this.beforeTest(thresholds, CosmosMetricCategory.DEFAULT); try { if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Test case only relevant for direct model."); } InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosItemResponse<InternalObjectNode> readResponse1 = container.readItem(properties.getId(), new PartitionKey(properties.get("mypk")), new CosmosItemRequestOptions(), InternalObjectNode.class); validateItemResponse(properties, readResponse1); CosmosDiagnosticsThresholds maxThresholds = new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofDays(1)); Tag operationTag = Tag.of(TagName.OperationStatusCode.toString(), "200"); Tag expectedSubStatusCodeOperationTag = Tag.of(TagName.OperationSubStatusCode.toString(), "0"); Tag requestTag = Tag.of(TagName.RequestStatusCode.toString(), "200/0"); this.assertMetrics("cosmos.client.op.latency", true, operationTag); this.assertMetrics("cosmos.client.op.latency", true, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.op.calls", true, operationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.req.rntbd.latency", expectRequestMetrics, requestTag); this.assertMetrics("cosmos.client.req.rntbd.backendLatency", expectRequestMetrics, requestTag); this.assertMetrics("cosmos.client.req.rntbd.requests", expectRequestMetrics, requestTag); Meter reportedRntbdRequestCharge = this.assertMetrics("cosmos.client.req.rntbd.RUs", expectRequestMetrics, requestTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readItemWithThresholdsApplied() throws Exception { CosmosDiagnosticsThresholds maxThresholds = new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofDays(1)); CosmosDiagnosticsThresholds minThresholds = new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ZERO); runReadItemTestWithThresholds(maxThresholds, false); runReadItemTestWithThresholds(minThresholds, true); } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void replaceItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(properties.get("mypk"))); CosmosItemResponse<InternalObjectNode> replace = container.replaceItem(properties, properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(BridgeInternal.getProperties(replace).get("newProp")).isEqualTo(newPropValue); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 1000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Replace"), Tag.of(TagName.RequestOperationType.toString(), "Document/Replace"), 0, 1000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void deleteItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "204"), Tag.of(TagName.RequestStatusCode.toString(), "204/0"), 0, 1000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Delete"), Tag.of(TagName.RequestOperationType.toString(), "Document/Delete"), 0, 1000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readAllItems() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); feedResponseIterator3.stream().collect(Collectors.toList()); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 3000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 10000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()) ); this.validateRequestActualItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId())); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.requests", true, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.RUs", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readAllItemsWithDetailMetrics() throws Exception { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.OPERATION_DETAILS, CosmosMetricCategory.REQUEST_DETAILS); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container .readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); feedResponseIterator3.stream().collect(Collectors.toList()); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 10000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 10000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()) ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.requests", true, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.RUs", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.timeline", true, queryPlanTag); this.assertMetrics("cosmos.client.op.maxItemCount", true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readAllItemsWithDetailMetricsWithExplicitPageSize() throws Exception { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.OPERATION_DETAILS, CosmosMetricCategory.REQUEST_DETAILS); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = new CosmosPagedIterable<>( container.asyncContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class), 10); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); feedResponseIterator3.stream().collect(Collectors.toList()); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 10000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 10000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()) ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.requests", true, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.RUs", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.timeline", true, queryPlanTag); this.assertMetrics("cosmos.client.op.maxItemCount", true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void queryItems() throws Exception { this.beforeTest(CosmosMetricCategory.ALL); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.queryItems(querySpec, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 100000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/queryItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 100000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/queryItems." + container.getId()) ); this.validateRequestActualItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/queryItems." + container.getId()) ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT * 10) public void itemPatchSuccess() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { PatchTest.ToDoActivity testItem = PatchTest.ToDoActivity.createRandomItem(this.container); PatchTest.ToDoActivity testItem1 = PatchTest.ToDoActivity.createRandomItem(this.container); PatchTest.ToDoActivity testItem2 = PatchTest.ToDoActivity.createRandomItem(this.container); int originalTaskNum = testItem.taskNum; int newTaskNum = originalTaskNum + 1; assertThat(testItem.children[1].status).isNull(); com.azure.cosmos.models.CosmosPatchOperations cosmosPatchOperations = com.azure.cosmos.models.CosmosPatchOperations.create(); cosmosPatchOperations.add("/children/0/CamelCase", "patched"); cosmosPatchOperations.remove("/description"); cosmosPatchOperations.replace("/taskNum", newTaskNum); cosmosPatchOperations.replace("/children/1", testItem1); cosmosPatchOperations.replace("/nestedChild", testItem2); cosmosPatchOperations.set("/valid", false); CosmosPatchItemRequestOptions options = new CosmosPatchItemRequestOptions(); CosmosItemResponse<PatchTest.ToDoActivity> response = this.container.patchItem( testItem.id, new PartitionKey(testItem.status), cosmosPatchOperations, options, PatchTest.ToDoActivity.class); assertThat(response.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); PatchTest.ToDoActivity patchedItem = response.getItem(); assertThat(patchedItem).isNotNull(); assertThat(patchedItem.children[0].camelCase).isEqualTo("patched"); assertThat(patchedItem.description).isNull(); assertThat(patchedItem.taskNum).isEqualTo(newTaskNum); assertThat(patchedItem.valid).isEqualTo(false); assertThat(patchedItem.children[1].id).isEqualTo(testItem1.id); assertThat(patchedItem.nestedChild.id).isEqualTo(testItem2.id); response = this.container.readItem( testItem.id, new PartitionKey(testItem.status), options, PatchTest.ToDoActivity.class); assertThat(response.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(response.getItem()).isEqualTo(patchedItem); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 3000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Patch"), Tag.of(TagName.RequestOperationType.toString(), "Document/Patch"), 0, 3000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void createItem_withBulk() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { int totalRequest = 5; List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); List<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> bulkResponse = Lists.newArrayList(this.container .executeBulkOperations(cosmosItemOperations, cosmosBulkExecutionOptions)); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 10000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Batch"), Tag.of(TagName.RequestOperationType.toString(), "Document/Batch"), 0, 10000 ); this.validateRequestActualItemCountMetrics( Tag.of(TagName.Operation.toString(), "Document/Batch"), Tag.of(TagName.PartitionKeyRangeId.toString(), "0"), Tag.of(TagName.PartitionKeyRangeId.toString(), "1")); } finally { this.afterTest(); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void batchMultipleItemExecution() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { TestDoc firstDoc = this.populateTestDoc(this.partitionKey1); TestDoc replaceDoc = this.getTestDocCopy(firstDoc); replaceDoc.setCost(replaceDoc.getCost() + 1); EventDoc eventDoc1 = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", this.partitionKey1); EventDoc readEventDoc = new EventDoc(UUID.randomUUID().toString(), 6, 14, "type2", this.partitionKey1); CosmosItemResponse<EventDoc> createResponse = container.createItem(readEventDoc, this.getPartitionKey(this.partitionKey1), null); assertThat(createResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); CosmosBatch batch = CosmosBatch.createCosmosBatch(this.getPartitionKey(this.partitionKey1)); batch.createItemOperation(firstDoc); batch.createItemOperation(eventDoc1); batch.replaceItemOperation(replaceDoc.getId(), replaceDoc); batch.readItemOperation(readEventDoc.getId()); CosmosBatchResponse batchResponse = container.executeCosmosBatch(batch); this.verifyBatchProcessed(batchResponse, 4); assertThat(batchResponse.getResults().get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.getResults().get(0).getItem(TestDoc.class)).isEqualTo(firstDoc); assertThat(batchResponse.getResults().get(1).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.getResults().get(1).getItem(EventDoc.class)).isEqualTo(eventDoc1); assertThat(batchResponse.getResults().get(2).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(batchResponse.getResults().get(2).getItem(TestDoc.class)).isEqualTo(replaceDoc); assertThat(batchResponse.getResults().get(3).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(batchResponse.getResults().get(3).getItem(EventDoc.class)).isEqualTo(readEventDoc); this.verifyByRead(container, replaceDoc); List<CosmosItemOperation> batchOperations = batch.getOperations(); for (int index = 0; index < batchOperations.size(); index++) { assertThat(batchResponse.getResults().get(index).getOperation()).isEqualTo(batchOperations.get(index)); } this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 3000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Batch"), Tag.of(TagName.RequestOperationType.toString(), "Document/Batch"), 0, 3000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForDefault() { this.beforeTest(CosmosMetricCategory.fromString("DeFAult")); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(5); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForDefaultPlusDetails() { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.fromString("RequestDetails"), CosmosMetricCategory.fromString("OperationDETAILS")); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(7); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesInvalidCategory() { String badCategoryName = "InvalidCategory"; try { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.fromString(badCategoryName)); fail("Should have thrown exception"); } catch (IllegalArgumentException argError) { assertThat(argError.getMessage()).contains(badCategoryName); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForAll() { this.beforeTest(CosmosMetricCategory.ALL); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(10); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectEndpoints)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.Legacy)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.AddressResolutions)).isEqualTo(true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void endpointMetricsAreDurable() throws IllegalAccessException { this.beforeTest(CosmosMetricCategory.ALL); try { if (client.asyncClient().getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { return; } RntbdTransportClient transportClient = (RntbdTransportClient) ReflectionUtils.getTransportClient(client); RntbdServiceEndpoint.Provider endpointProvider = (RntbdServiceEndpoint.Provider) ReflectionUtils.getRntbdEndpointProvider(transportClient); ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor = ReflectionUtils.getProactiveOpenConnectionsProcessor(transportClient); AddressSelector addressSelector = (AddressSelector) FieldUtils.readField(transportClient, "addressSelector", true); String address = "https: RntbdEndpoint firstEndpoint = endpointProvider.createIfAbsent(URI.create(address), new Uri(address), proactiveOpenConnectionsProcessor, Configs.getMinConnectionPoolSizePerEndpoint(), addressSelector); RntbdDurableEndpointMetrics firstDurableMetricsInstance = firstEndpoint.durableEndpointMetrics(); firstEndpoint.close(); assertThat(firstEndpoint.durableEndpointMetrics().getEndpoint()).isNull(); RntbdEndpoint secondEndpoint = endpointProvider.createIfAbsent(URI.create(address), new Uri(address), proactiveOpenConnectionsProcessor, Configs.getMinConnectionPoolSizePerEndpoint(), addressSelector); assertThat(firstEndpoint).isNotSameAs(secondEndpoint); assertThat(firstDurableMetricsInstance).isSameAs(secondEndpoint.durableEndpointMetrics()); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForAllLatebound() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(5); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); this.inputMetricsOptions .setMetricCategories(CosmosMetricCategory.ALL) .removeMetricCategories(CosmosMetricCategory.OPERATION_DETAILS) .addMetricCategories(CosmosMetricCategory.OPERATION_DETAILS, CosmosMetricCategory.REQUEST_DETAILS) .configureDefaultPercentiles(0.9) .enableHistogramsByDefault(false) .setEnabled(true); assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(10); clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); } finally { this.afterTest(); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void invalidMeterNameThrows() { try { CosmosMetricName.fromString("InvalidMeterName"); fail("Should have thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("InvalidMeterName"); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void invalidMeterCategoryThrows() { try { CosmosMetricCategory.fromString("InvalidMeterCategory"); fail("Should have thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("InvalidMeterCategory"); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void invalidMeterTagNameThrows() { try { CosmosMetricTagName.fromString("InvalidMeterTagName"); fail("Should have thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("InvalidMeterTagName"); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void meterTagNameFromStringConversion() { assertThat(CosmosMetricTagName.fromString("aLl ")) .isSameAs(CosmosMetricTagName.ALL); assertThat(CosmosMetricTagName.fromString("Default")) .isSameAs(CosmosMetricTagName.DEFAULT); assertThat(CosmosMetricTagName.fromString("minimum")) .isSameAs(CosmosMetricTagName.MINIMUM); assertThat(CosmosMetricTagName.fromString("IsForceCollectionRoutingMapRefresh")) .isSameAs(CosmosMetricTagName.ADDRESS_RESOLUTION_COLLECTION_MAP_REFRESH); assertThat(CosmosMetricTagName.fromString("isForcerefresh")) .isSameAs(CosmosMetricTagName.ADDRESS_RESOLUTION_FORCED_REFRESH); assertThat(CosmosMetricTagName.fromString("ClientCorrelationID")) .isSameAs(CosmosMetricTagName.CLIENT_CORRELATION_ID); assertThat(CosmosMetricTagName.fromString("container")) .isSameAs(CosmosMetricTagName.CONTAINER); assertThat(CosmosMetricTagName.fromString(" ConsistencyLevel")) .isSameAs(CosmosMetricTagName.CONSISTENCY_LEVEL); assertThat(CosmosMetricTagName.fromString("operation")) .isSameAs(CosmosMetricTagName.OPERATION); assertThat(CosmosMetricTagName.fromString("OperationStatusCode")) .isSameAs(CosmosMetricTagName.OPERATION_STATUS_CODE); assertThat(CosmosMetricTagName.fromString("PartitionKeyRangeId")) .isSameAs(CosmosMetricTagName.PARTITION_KEY_RANGE_ID); assertThat(CosmosMetricTagName.fromString("regionname")) .isSameAs(CosmosMetricTagName.REGION_NAME); assertThat(CosmosMetricTagName.fromString("RequestOperationType")) .isSameAs(CosmosMetricTagName.REQUEST_OPERATION_TYPE); assertThat(CosmosMetricTagName.fromString("requestStatusCode")) .isSameAs(CosmosMetricTagName.REQUEST_STATUS_CODE); assertThat(CosmosMetricTagName.fromString("serviceaddress")) .isSameAs(CosmosMetricTagName.SERVICE_ADDRESS); assertThat(CosmosMetricTagName.fromString("serviceEndpoint")) .isSameAs(CosmosMetricTagName.SERVICE_ENDPOINT); assertThat(CosmosMetricTagName.fromString("partitionID")) .isSameAs(CosmosMetricTagName.PARTITION_ID); assertThat(CosmosMetricTagName.fromString("REPLICAid")) .isSameAs(CosmosMetricTagName.REPLICA_ID); } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void meterCategoryFromStringConversion() { assertThat(CosmosMetricCategory.fromString("aLl ")) .isSameAs(CosmosMetricCategory.ALL); assertThat(CosmosMetricCategory.fromString("Default")) .isSameAs(CosmosMetricCategory.DEFAULT); assertThat(CosmosMetricCategory.fromString("minimum")) .isSameAs(CosmosMetricCategory.MINIMUM); assertThat(CosmosMetricCategory.fromString("operationsummary ")) .isSameAs(CosmosMetricCategory.OPERATION_SUMMARY); assertThat(CosmosMetricCategory.fromString("operationDetails")) .isSameAs(CosmosMetricCategory.OPERATION_DETAILS); assertThat(CosmosMetricCategory.fromString("RequestSummary")) .isSameAs(CosmosMetricCategory.REQUEST_SUMMARY); assertThat(CosmosMetricCategory.fromString("RequestDetails")) .isSameAs(CosmosMetricCategory.REQUEST_DETAILS); assertThat(CosmosMetricCategory.fromString("DirectChannels")) .isSameAs(CosmosMetricCategory.DIRECT_CHANNELS); assertThat(CosmosMetricCategory.fromString("DirectRequests")) .isSameAs(CosmosMetricCategory.DIRECT_REQUESTS); assertThat(CosmosMetricCategory.fromString("DirectEndpoints")) .isSameAs(CosmosMetricCategory.DIRECT_ENDPOINTS); assertThat(CosmosMetricCategory.fromString("DirectAddressResolutions")) .isSameAs(CosmosMetricCategory.DIRECT_ADDRESS_RESOLUTIONS); assertThat(CosmosMetricCategory.fromString("system")) .isSameAs(CosmosMetricCategory.SYSTEM); assertThat(CosmosMetricCategory.fromString("Legacy")) .isSameAs(CosmosMetricCategory.LEGACY); } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void meterNameFromStringConversion() { assertThat(CosmosMetricName.fromString("cosmos.client.op.laTency")) .isSameAs(CosmosMetricName.OPERATION_SUMMARY_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.client.op.cAlls")) .isSameAs(CosmosMetricName.OPERATION_SUMMARY_CALLS); assertThat(CosmosMetricName.fromString("cosmos.client.op.rus")) .isSameAs(CosmosMetricName.OPERATION_SUMMARY_REQUEST_CHARGE); assertThat(CosmosMetricName.fromString("cosmos.client.OP.actualItemCount")) .isSameAs(CosmosMetricName.OPERATION_DETAILS_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.op.MAXItemCount")) .isSameAs(CosmosMetricName.OPERATION_DETAILS_MAX_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.op.REGIONScontacted")) .isSameAs(CosmosMetricName.OPERATION_DETAILS_REGIONS_CONTACTED); assertThat(CosmosMetricName.fromString("cosmos.client.req.reqPaylOADSize")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_SIZE_REQUEST); assertThat(CosmosMetricName.fromString("cosmos.client.req.rspPayloadSIZE")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_SIZE_RESPONSE); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.backendLatency")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_BACKEND_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.LAtency")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.RUS")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_REQUEST_CHARGE); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.ReQUEsts")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_REQUESTS); assertThat(CosmosMetricName.fromString("cosmos.client.req.rntbd.TIMEline")) .isSameAs(CosmosMetricName.REQUEST_DETAILS_DIRECT_TIMELINE); assertThat(CosmosMetricName.fromString("cosmos.client.Req.rntbd.actualItemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.req.rntbd.actualITemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.gw.LAtency")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.gw.RUS")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_REQUEST_CHARGE); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.gw.ReQUEsts")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_REQUESTS); assertThat(CosmosMetricName.fromString("cosmos.client.req.gw.tiMELine")) .isSameAs(CosmosMetricName.REQUEST_DETAILS_GATEWAY_TIMELINE); assertThat(CosmosMetricName.fromString("cosmos.client.Req.gw.actualItemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.req.gw.actualITemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.addressResolution.latency")) .isSameAs(CosmosMetricName.DIRECT_ADDRESS_RESOLUTION_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.addressResolution.requests")) .isSameAs(CosmosMetricName.DIRECT_ADDRESS_RESOLUTION_REQUESTS); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.channels.acquired.COUNT")) .isSameAs(CosmosMetricName.DIRECT_CHANNELS_ACQUIRED_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.channels.available.COUNT")) .isSameAs(CosmosMetricName.DIRECT_CHANNELS_AVAILABLE_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.channels.closed.COUNT")) .isSameAs(CosmosMetricName.DIRECT_CHANNELS_CLOSED_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.endpoints.COUNT")) .isSameAs(CosmosMetricName.DIRECT_ENDPOINTS_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.endpoints.evicted")) .isSameAs(CosmosMetricName.DIRECT_ENDPOINTS_EVICTED); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.concurrent.count")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_CONCURRENT_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.LAtency")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.FAIled.latency")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_LATENCY_FAILED); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.successful.latency")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_LATENCY_SUCCESS); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.queued.count")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_QUEUED_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.req.RSPsize")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_SIZE_RESPONSE); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.req.reqsize")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_SIZE_REQUEST); } @Test(groups = { "unit" }, timeOut = TIMEOUT) private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); return new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); } private void validateItemResponse(InternalObjectNode containerProperties, CosmosItemResponse<InternalObjectNode> createResponse) { assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(containerProperties.getId()); } private void validateReadManyFeedResponse( List<InternalObjectNode> createdDocs, FeedResponse<InternalObjectNode> readManyResponse) { assertThat(readManyResponse).isNotNull(); assertThat(readManyResponse.getResults()).isNotNull(); List<InternalObjectNode> docsFromResponse = readManyResponse.getResults(); assertThat(docsFromResponse).hasSize(createdDocs.size()); for (InternalObjectNode doc: createdDocs) { assertThat(docsFromResponse.stream().anyMatch(r -> r.getId() != null && r.getId().equals(doc.getId()))); } } private void validateItemCountMetrics(Tag expectedOperationTag) { if (this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)) { this.assertMetrics("cosmos.client.op.maxItemCount", true, expectedOperationTag); this.assertMetrics("cosmos.client.op.actualItemCount", true, expectedOperationTag); } } private void validateRequestActualItemCountMetrics(Tag... expectedRequestTags) { if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)) { if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() == ConnectionMode.DIRECT) { for (Tag expectedRequestTag : expectedRequestTags) { this.assertMetrics("cosmos.client.req.rntbd.actualItemCount", true, expectedRequestTag); } } else { for (Tag expectedRequestTag : expectedRequestTags) { this.assertMetrics("cosmos.client.req.gw.actualItemCount", true, expectedRequestTag); } } } } private void validateReasonableRUs(Meter reportedRequestChargeMeter, int expectedMinRu, int expectedMaxRu) { List<Measurement> measurements = new ArrayList<>(); reportedRequestChargeMeter.measure().forEach(measurements::add); logger.info("RequestedRequestChargeMeter: {} {}", reportedRequestChargeMeter, reportedRequestChargeMeter.getId()); assertThat(measurements.size()).isGreaterThan(0); for (int i = 0; i < measurements.size(); i++) { assertThat(measurements.get(i).getValue()).isGreaterThanOrEqualTo(expectedMinRu); assertThat(measurements.get(i).getValue()).isLessThanOrEqualTo(expectedMaxRu); } } private void validateMetrics(Tag expectedOperationTag, Tag expectedRequestTag, int minRu, int maxRu) { this.assertMetrics("cosmos.client.op.latency", true, expectedOperationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedOperationTag); if (expectedOperationTag.getKey() == "OperationStatusCode" && ("200".equals(expectedOperationTag.getValue()) || "201".equals(expectedOperationTag.getValue()))) { Tag expectedSubStatusCodeOperationTag = Tag.of(TagName.OperationSubStatusCode.toString(), "0"); this.assertMetrics("cosmos.client.op.latency", true, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedSubStatusCodeOperationTag); } Meter reportedOpRequestCharge = this.assertMetrics( "cosmos.client.op.RUs", true, expectedOperationTag); validateReasonableRUs(reportedOpRequestCharge, minRu, maxRu); if (this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)) { this.assertMetrics("cosmos.client.op.regionsContacted", true, expectedOperationTag); this.assertMetrics( "cosmos.client.op.regionsContacted", true, Tag.of(TagName.RegionName.toString(), this.preferredRegion.toLowerCase(Locale.ROOT))); } if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)) { this.assertMetrics( "cosmos.client.req.reqPayloadSize", true, expectedOperationTag); this.assertMetrics( "cosmos.client.req.rspPayloadSize", true, expectedOperationTag); } if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() == ConnectionMode.DIRECT) { this.assertMetrics("cosmos.client.req.rntbd.latency", true, expectedRequestTag); this.assertMetrics( "cosmos.client.req.rntbd.latency", true, Tag.of(TagName.RegionName.toString(), this.preferredRegion.toLowerCase(Locale.ROOT))); this.assertMetrics("cosmos.client.req.rntbd.backendLatency", true, expectedRequestTag); this.assertMetrics("cosmos.client.req.rntbd.requests", true, expectedRequestTag); Meter reportedRntbdRequestCharge = this.assertMetrics("cosmos.client.req.rntbd.RUs", true, expectedRequestTag); validateReasonableRUs(reportedRntbdRequestCharge, minRu, maxRu); if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)) { this.assertMetrics("cosmos.client.req.rntbd.timeline", true, expectedRequestTag); } } else { this.assertMetrics("cosmos.client.req.gw.latency", true, expectedRequestTag); if (this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)) { this.assertMetrics( "cosmos.client.req.gw.latency", true, Tag.of(TagName.RegionName.toString(), this.preferredRegion.toLowerCase(Locale.ROOT))); } this.assertMetrics("cosmos.client.req.gw.backendLatency", false, expectedRequestTag); this.assertMetrics("cosmos.client.req.gw.requests", true, expectedRequestTag); Meter reportedGatewayRequestCharge = this.assertMetrics("cosmos.client.req.gw.RUs", true, expectedRequestTag); validateReasonableRUs(reportedGatewayRequestCharge, minRu, maxRu); if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)) { this.assertMetrics("cosmos.client.req.gw.timeline", true, expectedRequestTag); } } } private Meter assertMetrics(String prefix, boolean expectedToFind) { return assertMetrics(prefix, expectedToFind, null); } private Meter assertMetrics(String prefix, boolean expectedToFind, Tag withTag) { assertThat(this.meterRegistry).isNotNull(); assertThat(this.meterRegistry.getMeters()).isNotNull(); List<Meter> meters = this.meterRegistry.getMeters().stream().collect(Collectors.toList()); if (expectedToFind) { assertThat(meters.size()).isGreaterThan(0); assertTagInAllMeters(meters, prefix); } List<Meter> meterPrefixMatches = meters .stream() .filter(meter -> meter.getId().getName().startsWith(prefix)) .collect(Collectors.toList()); List<Meter> meterMatches = meterPrefixMatches .stream() .filter(meter -> (withTag == null || meter.getId().getTags().contains(withTag)) && meter.measure().iterator().next().getValue() > 0) .collect(Collectors.toList()); if (expectedToFind) { if (meterMatches.size() == 0) { String message = String.format( "No meter found for the expected constraints - prefix '%s', withTag '%s'", prefix, withTag); logger.error(message); logger.info("Meters matching the prefix"); meterPrefixMatches.forEach(meter -> logger.info("{} has measurements {}", meter.getId(), meter.measure().iterator().hasNext())); fail(message); } if (meterMatches.size() > 1) { StringBuilder sb = new StringBuilder(); final AtomicReference<Meter> exactMatchMeter = new AtomicReference<>(null); meterMatches.forEach(m -> { if (exactMatchMeter.get() == null && m.getId().getName().equals(prefix)) { exactMatchMeter.set(m); } String message = String.format( "Found more than one meter '%s' for prefix '%s' withTag '%s' --> '%s'", m.getId(), prefix, withTag, m); sb.append(message); sb.append(System.getProperty("line.separator")); logger.info(message); }); if (exactMatchMeter.get() != null) { logger.info("Found exact match {}", exactMatchMeter); return exactMatchMeter.get(); } } return meterMatches.get(0); } else { if (meterMatches.size() > 0) { StringBuilder sb = new StringBuilder(); meterMatches.forEach(m -> { String message = String.format( "Found unexpected meter '%s' for prefix '%s' withTag '%s' --> '%s'", m, prefix, withTag, m); sb.append(message); sb.append(System.getProperty("line.separator")); logger.error(message); }); fail(sb.toString()); } assertThat(meterMatches.size()).isEqualTo(0); return null; } } private void assertTagInAllMeters(List<Meter> meters, String prefix) { List<Meter> meterMatches = meters .stream() .filter(meter -> meter.getId().getName().equals(prefix) && meter.getId().getTags().contains(this.clientCorrelationTag)) .collect(Collectors.toList()); if (meterMatches.size() > 0) { Set<String> possibleTags = new HashSet<>(); for (Tag tag : meterMatches.get(0).getId().getTags()) { possibleTags.add(tag.getKey()); } List<Meter> metersTagPresent = meterMatches .stream() .filter(meter -> { int numTags = 0; for (Tag tag : meter.getId().getTags()) { if (!possibleTags.contains(tag.getKey())) { return false; } numTags++; } return numTags == possibleTags.size(); } ) .collect(Collectors.toList()); if (metersTagPresent.size() != meterMatches.size()) { logger.error("MetersTagPresent"); for (Meter meter : metersTagPresent) { logger.error("Meter: {}", meter.getId()); } logger.error("MeterMatches"); for (Meter meter : meterMatches) { logger.error("Meter: {}", meter.getId()); } } assertThat(metersTagPresent.size()).isEqualTo(meterMatches.size()); } } private List<String> getAvailableWriteRegionNames(RxDocumentClientImpl rxDocumentClient) { try { 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 availableWriteLocations = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteLocations"); availableWriteLocations.setAccessible(true); @SuppressWarnings("unchecked") List<String> list = (List<String>) availableWriteLocations.get(locationInfo); return list; } catch (Exception error) { fail(error.toString()); return null; } } }
class ClientMetricsTest extends BatchTestBase { private CosmosClient client; private CosmosContainer container; private String databaseId; private String containerId; private MeterRegistry meterRegistry; private String preferredRegion; private CosmosClientTelemetryConfig inputClientTelemetryConfig; private CosmosMicrometerMetricsOptions inputMetricsOptions; private Tag clientCorrelationTag; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public ClientMetricsTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } private EnumSet<MetricCategory> getEffectiveMetricCategories() { return ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .getMetricCategories(this.inputClientTelemetryConfig); } public void beforeTest(CosmosMetricCategory... metricCategories) { beforeTest(null, metricCategories); } public void beforeTest( CosmosDiagnosticsThresholds thresholds, CosmosMetricCategory... metricCategories) { assertThat(this.client).isNull(); assertThat(this.meterRegistry).isNull(); this.meterRegistry = ConsoleLoggingRegistryFactory.create(1); this.inputMetricsOptions = new CosmosMicrometerMetricsOptions() .meterRegistry(this.meterRegistry) .setMetricCategories(metricCategories) .configureDefaultTagNames( CosmosMetricTagName.DEFAULT, CosmosMetricTagName.PARTITION_ID, CosmosMetricTagName.REPLICA_ID, CosmosMetricTagName.OPERATION_SUB_STATUS_CODE, CosmosMetricTagName.PARTITION_KEY_RANGE_ID); this.inputClientTelemetryConfig = new CosmosClientTelemetryConfig() .metricsOptions(this.inputMetricsOptions); if (thresholds != null) { this.inputClientTelemetryConfig.diagnosticsThresholds(thresholds); this.inputMetricsOptions.applyDiagnosticThresholdsForTransportLevelMeters(true); } this.client = getClientBuilder() .clientTelemetryConfig(inputClientTelemetryConfig) .buildClient(); assertThat( ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(this.client.asyncClient()) ).isSameAs(this.getEffectiveMetricCategories()); AsyncDocumentClient asyncDocumentClient = ReflectionUtils.getAsyncDocumentClient(this.client.asyncClient()); RxDocumentClientImpl rxDocumentClient = (RxDocumentClientImpl) asyncDocumentClient; List<String> writeRegions = this.getAvailableWriteRegionNames(rxDocumentClient); assertThat(writeRegions).isNotNull().isNotEmpty(); this.preferredRegion = writeRegions.iterator().next(); if (databaseId == null) { CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); this.databaseId = asyncContainer.getDatabase().getId(); this.containerId = asyncContainer.getId(); } this.clientCorrelationTag = client.asyncClient().getClientCorrelationTag(); container = client.getDatabase(databaseId).getContainer(containerId); } public void afterTest() { this.container = null; CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { this.client.close(); } this.client = null; MeterRegistry meterRegistrySnapshot = this.meterRegistry; if (meterRegistrySnapshot != null) { meterRegistrySnapshot.clear(); meterRegistrySnapshot.close(); } this.meterRegistry = null; } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void maxValueExceedingDefinedLimitStillWorksWithoutException() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { Tag dummyOperationTag = Tag.of(TagName.Operation.toString(), "TestDummy"); Timer latencyMeter = Timer .builder("cosmos.client.op.latency") .description("Operation latency") .maximumExpectedValue(Duration.ofSeconds(300)) .publishPercentiles(0.95, 0.99) .publishPercentileHistogram(true) .tags(Collections.singleton(dummyOperationTag)) .register(this.meterRegistry); latencyMeter.record(Duration.ofSeconds(600)); Meter requestLatencyMeter = this.assertMetrics( "cosmos.client.op.latency", true, dummyOperationTag); List<Measurement> measurements = new ArrayList<>(); requestLatencyMeter.measure().forEach(measurements::add); int expectedMeasurementCount = 3; if (measurements.size() < expectedMeasurementCount) { logger.error("Size should have been 3 but was {}", measurements.size()); for (int i = 0; i < measurements.size(); i++) { Measurement m = measurements.get(i); logger.error( "{}: {}", i, m); } } assertThat(measurements.size()).isGreaterThanOrEqualTo(expectedMeasurementCount); assertThat(measurements.get(0).getStatistic().getTagValueRepresentation()).isEqualTo("count"); assertThat(measurements.get(0).getValue()).isEqualTo(1); assertThat(measurements.get(1).getStatistic().getTagValueRepresentation()).isEqualTo("total"); assertThat(measurements.get(1).getValue()).isEqualTo(600 * 1000); assertThat(measurements.get(2).getStatistic().getTagValueRepresentation()).isEqualTo("max"); assertThat(measurements.get(2).getValue()).isEqualTo(600 * 1000); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void createItem() throws Exception { boolean[] disableLatencyMeterTestCases = { false, true }; for (boolean disableLatencyMeter: disableLatencyMeterTestCases) { this.beforeTest(CosmosMetricCategory.DEFAULT); if (disableLatencyMeter) { this.inputMetricsOptions .configureMeter( CosmosMetricName.fromString(CosmosMetricName.OPERATION_SUMMARY_LATENCY.toString().toUpperCase(Locale.ROOT)), new CosmosMicrometerMeterOptions().setEnabled(false)); } try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); Tag expectedOperationTag = Tag.of(TagName.OperationStatusCode.toString(), "201"); this.assertMetrics("cosmos.client.op.latency", !disableLatencyMeter, expectedOperationTag); Tag expectedSubStatusCodeOperationTag = Tag.of(TagName.OperationSubStatusCode.toString(), "0"); this.assertMetrics("cosmos.client.op.latency", !disableLatencyMeter, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedOperationTag); if (!disableLatencyMeter) { Tag expectedRequestTag = Tag.of(TagName.RequestStatusCode.toString(), "201/0"); this.validateMetrics( expectedOperationTag, expectedRequestTag, 0, 300 ); if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() == ConnectionMode.DIRECT) { Meter foundMeter = this.assertMetrics( "cosmos.client.req.rntbd.latency", true, expectedRequestTag); assertThat(foundMeter).isNotNull(); boolean replicaIdDimensionExists = foundMeter .getId() .getTags() .stream() .anyMatch(tag -> tag.getKey().equals(TagName.ReplicaId.toString()) && !tag.getValue().equals("NONE")); assertThat(replicaIdDimensionExists) .isEqualTo(true); } this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Create"), Tag.of(TagName.RequestOperationType.toString(), "Document/Create"), 0, 300 ); } } finally { this.afterTest(); } } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void createItemWithAllMetrics() throws Exception { boolean[] suppressConsistencyLevelTagTestCases = { false, true }; for (boolean suppressConsistencyLevelTag: suppressConsistencyLevelTagTestCases) { this.beforeTest(CosmosMetricCategory.ALL); this .inputMetricsOptions .configureDefaultTagNames(CosmosMetricTagName.ALL); if (suppressConsistencyLevelTag) { this .inputMetricsOptions .configureMeter( CosmosMetricName.OPERATION_SUMMARY_LATENCY, new CosmosMicrometerMeterOptions() .suppressTagNames(CosmosMetricTagName.fromString("ConsistencyLevel")) .enableHistograms(false) .configurePercentiles(0.99, 0.999)); } try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); validateItemResponse(properties, itemResponse); properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse1 = container.createItem(properties, new CosmosItemRequestOptions()); validateItemResponse(properties, itemResponse1); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "201"), Tag.of(TagName.RequestStatusCode.toString(), "201/0"), 0, 300 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Create"), Tag.of(TagName.RequestOperationType.toString(), "Document/Create"), 0, 300 ); String expectedConsistencyLevel = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getEffectiveConsistencyLevel( client.asyncClient(), OperationType.Create, null) .toString(); Tag expectedConsistencyTag = Tag.of(TagName.ConsistencyLevel.toString(), expectedConsistencyLevel); this.assertMetrics( "cosmos.client.op.latency", !suppressConsistencyLevelTag, expectedConsistencyTag); this.assertMetrics( "cosmos.client.op.calls", true, expectedConsistencyTag); } finally { this.afterTest(); } } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosItemResponse<InternalObjectNode> readResponse1 = container.readItem(properties.getId(), new PartitionKey(properties.get("mypk")), new CosmosItemRequestOptions(), InternalObjectNode.class); validateItemResponse(properties, readResponse1); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 500 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Read"), Tag.of(TagName.RequestOperationType.toString(), "Document/Read"), 0, 500 ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readManySingleItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); List<CosmosItemIdentity> tuplesToBeRead = new ArrayList<>(); tuplesToBeRead.add(new CosmosItemIdentity( new PartitionKey(properties.get("mypk")), properties.getId() )); FeedResponse<InternalObjectNode> readManyResponse = container.readMany( tuplesToBeRead, new CosmosReadManyRequestOptions(), InternalObjectNode.class); validateReadManyFeedResponse(Arrays.asList(properties), readManyResponse); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 500 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/readMany"), Tag.of(TagName.RequestOperationType.toString(), "Document/Read"), 0, 500 ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readManyMultipleItems() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); List<InternalObjectNode> createdDocs = new ArrayList<>(); List<CosmosItemIdentity> tuplesToBeRead = new ArrayList<>(); try { for (int i = 0; i < 20; i++) { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); createdDocs.add(properties); tuplesToBeRead.add(new CosmosItemIdentity( new PartitionKey(properties.get("mypk")), properties.getId() )); } FeedResponse<InternalObjectNode> readManyResponse = container.readMany( tuplesToBeRead, new CosmosReadManyRequestOptions(), InternalObjectNode.class); validateReadManyFeedResponse(createdDocs, readManyResponse); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 500 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/readMany"), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 500 ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } private void runReadItemTestWithThresholds( CosmosDiagnosticsThresholds thresholds, boolean expectRequestMetrics ) { this.beforeTest(thresholds, CosmosMetricCategory.DEFAULT); try { if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Test case only relevant for direct model."); } InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosItemResponse<InternalObjectNode> readResponse1 = container.readItem(properties.getId(), new PartitionKey(properties.get("mypk")), new CosmosItemRequestOptions(), InternalObjectNode.class); validateItemResponse(properties, readResponse1); CosmosDiagnosticsThresholds maxThresholds = new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofDays(1)); Tag operationTag = Tag.of(TagName.OperationStatusCode.toString(), "200"); Tag expectedSubStatusCodeOperationTag = Tag.of(TagName.OperationSubStatusCode.toString(), "0"); Tag requestTag = Tag.of(TagName.RequestStatusCode.toString(), "200/0"); this.assertMetrics("cosmos.client.op.latency", true, operationTag); this.assertMetrics("cosmos.client.op.latency", true, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.op.calls", true, operationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.req.rntbd.latency", expectRequestMetrics, requestTag); this.assertMetrics("cosmos.client.req.rntbd.backendLatency", expectRequestMetrics, requestTag); this.assertMetrics("cosmos.client.req.rntbd.requests", expectRequestMetrics, requestTag); Meter reportedRntbdRequestCharge = this.assertMetrics("cosmos.client.req.rntbd.RUs", expectRequestMetrics, requestTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readItemWithThresholdsApplied() throws Exception { CosmosDiagnosticsThresholds maxThresholds = new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofDays(1)); CosmosDiagnosticsThresholds minThresholds = new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ZERO); runReadItemTestWithThresholds(maxThresholds, false); runReadItemTestWithThresholds(minThresholds, true); } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void replaceItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); CosmosItemResponse<InternalObjectNode> itemResponse = container.createItem(properties); validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(properties.get("mypk"))); CosmosItemResponse<InternalObjectNode> replace = container.replaceItem(properties, properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(BridgeInternal.getProperties(replace).get("newProp")).isEqualTo(newPropValue); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 1000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Replace"), Tag.of(TagName.RequestOperationType.toString(), "Document/Replace"), 0, 1000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void deleteItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse<?> deleteResponse = container.deleteItem(properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "204"), Tag.of(TagName.RequestStatusCode.toString(), "204/0"), 0, 1000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Delete"), Tag.of(TagName.RequestOperationType.toString(), "Document/Delete"), 0, 1000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readAllItems() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); feedResponseIterator3.stream().collect(Collectors.toList()); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 3000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 10000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()) ); this.validateRequestActualItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId())); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.requests", true, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.RUs", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readAllItemsWithDetailMetrics() throws Exception { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.OPERATION_DETAILS, CosmosMetricCategory.REQUEST_DETAILS); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container .readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); feedResponseIterator3.stream().collect(Collectors.toList()); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 10000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 10000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()) ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.requests", true, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.RUs", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.timeline", true, queryPlanTag); this.assertMetrics("cosmos.client.op.maxItemCount", true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readAllItemsWithDetailMetricsWithExplicitPageSize() throws Exception { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.OPERATION_DETAILS, CosmosMetricCategory.REQUEST_DETAILS); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = new CosmosPagedIterable<>( container.asyncContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class), 10); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); feedResponseIterator3.stream().collect(Collectors.toList()); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 10000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 10000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/ReadFeed/readAllItems." + container.getId()) ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.requests", true, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.RUs", false, queryPlanTag); this.assertMetrics("cosmos.client.req.gw.timeline", true, queryPlanTag); this.assertMetrics("cosmos.client.op.maxItemCount", true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void queryItems() throws Exception { this.beforeTest(CosmosMetricCategory.ALL); try { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> feedResponseIterator1 = container.queryItems(query, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<InternalObjectNode> feedResponseIterator3 = container.queryItems(querySpec, cosmosQueryRequestOptions, InternalObjectNode.class); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 100000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/queryItems." + container.getId()), Tag.of(TagName.RequestOperationType.toString(), "Document/Query"), 0, 100000 ); this.validateItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/queryItems." + container.getId()) ); this.validateRequestActualItemCountMetrics( Tag.of( TagName.Operation.toString(), "Document/Query/queryItems." + container.getId()) ); Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection/QueryPlan"); this.assertMetrics("cosmos.client.req.gw", true, queryPlanTag); this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); } finally { this.afterTest(); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT * 10) public void itemPatchSuccess() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { PatchTest.ToDoActivity testItem = PatchTest.ToDoActivity.createRandomItem(this.container); PatchTest.ToDoActivity testItem1 = PatchTest.ToDoActivity.createRandomItem(this.container); PatchTest.ToDoActivity testItem2 = PatchTest.ToDoActivity.createRandomItem(this.container); int originalTaskNum = testItem.taskNum; int newTaskNum = originalTaskNum + 1; assertThat(testItem.children[1].status).isNull(); com.azure.cosmos.models.CosmosPatchOperations cosmosPatchOperations = com.azure.cosmos.models.CosmosPatchOperations.create(); cosmosPatchOperations.add("/children/0/CamelCase", "patched"); cosmosPatchOperations.remove("/description"); cosmosPatchOperations.replace("/taskNum", newTaskNum); cosmosPatchOperations.replace("/children/1", testItem1); cosmosPatchOperations.replace("/nestedChild", testItem2); cosmosPatchOperations.set("/valid", false); CosmosPatchItemRequestOptions options = new CosmosPatchItemRequestOptions(); CosmosItemResponse<PatchTest.ToDoActivity> response = this.container.patchItem( testItem.id, new PartitionKey(testItem.status), cosmosPatchOperations, options, PatchTest.ToDoActivity.class); assertThat(response.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); PatchTest.ToDoActivity patchedItem = response.getItem(); assertThat(patchedItem).isNotNull(); assertThat(patchedItem.children[0].camelCase).isEqualTo("patched"); assertThat(patchedItem.description).isNull(); assertThat(patchedItem.taskNum).isEqualTo(newTaskNum); assertThat(patchedItem.valid).isEqualTo(false); assertThat(patchedItem.children[1].id).isEqualTo(testItem1.id); assertThat(patchedItem.nestedChild.id).isEqualTo(testItem2.id); response = this.container.readItem( testItem.id, new PartitionKey(testItem.status), options, PatchTest.ToDoActivity.class); assertThat(response.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(response.getItem()).isEqualTo(patchedItem); this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 3000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Patch"), Tag.of(TagName.RequestOperationType.toString(), "Document/Patch"), 0, 3000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void createItem_withBulk() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { int totalRequest = 5; List<com.azure.cosmos.models.CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); BatchTestBase.TestDoc testDoc = this.populateTestDoc(partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); partitionKey = UUID.randomUUID().toString(); BatchTestBase.EventDoc eventDoc = new BatchTestBase.EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); cosmosItemOperations.add(CosmosBulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey))); } CosmosBulkExecutionOptions cosmosBulkExecutionOptions = new CosmosBulkExecutionOptions(); List<com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest>> bulkResponse = Lists.newArrayList(this.container .executeBulkOperations(cosmosItemOperations, cosmosBulkExecutionOptions)); assertThat(bulkResponse.size()).isEqualTo(totalRequest * 2); for (com.azure.cosmos.models.CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse : bulkResponse) { com.azure.cosmos.models.CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); } this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 10000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Batch"), Tag.of(TagName.RequestOperationType.toString(), "Document/Batch"), 0, 10000 ); this.validateRequestActualItemCountMetrics( Tag.of(TagName.Operation.toString(), "Document/Batch"), Tag.of(TagName.PartitionKeyRangeId.toString(), "0"), Tag.of(TagName.PartitionKeyRangeId.toString(), "1")); } finally { this.afterTest(); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void batchMultipleItemExecution() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { TestDoc firstDoc = this.populateTestDoc(this.partitionKey1); TestDoc replaceDoc = this.getTestDocCopy(firstDoc); replaceDoc.setCost(replaceDoc.getCost() + 1); EventDoc eventDoc1 = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", this.partitionKey1); EventDoc readEventDoc = new EventDoc(UUID.randomUUID().toString(), 6, 14, "type2", this.partitionKey1); CosmosItemResponse<EventDoc> createResponse = container.createItem(readEventDoc, this.getPartitionKey(this.partitionKey1), null); assertThat(createResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); CosmosBatch batch = CosmosBatch.createCosmosBatch(this.getPartitionKey(this.partitionKey1)); batch.createItemOperation(firstDoc); batch.createItemOperation(eventDoc1); batch.replaceItemOperation(replaceDoc.getId(), replaceDoc); batch.readItemOperation(readEventDoc.getId()); CosmosBatchResponse batchResponse = container.executeCosmosBatch(batch); this.verifyBatchProcessed(batchResponse, 4); assertThat(batchResponse.getResults().get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.getResults().get(0).getItem(TestDoc.class)).isEqualTo(firstDoc); assertThat(batchResponse.getResults().get(1).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.getResults().get(1).getItem(EventDoc.class)).isEqualTo(eventDoc1); assertThat(batchResponse.getResults().get(2).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(batchResponse.getResults().get(2).getItem(TestDoc.class)).isEqualTo(replaceDoc); assertThat(batchResponse.getResults().get(3).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(batchResponse.getResults().get(3).getItem(EventDoc.class)).isEqualTo(readEventDoc); this.verifyByRead(container, replaceDoc); List<CosmosItemOperation> batchOperations = batch.getOperations(); for (int index = 0; index < batchOperations.size(); index++) { assertThat(batchResponse.getResults().get(index).getOperation()).isEqualTo(batchOperations.get(index)); } this.validateMetrics( Tag.of(TagName.OperationStatusCode.toString(), "200"), Tag.of(TagName.RequestStatusCode.toString(), "200/0"), 0, 3000 ); this.validateMetrics( Tag.of( TagName.Operation.toString(), "Document/Batch"), Tag.of(TagName.RequestOperationType.toString(), "Document/Batch"), 0, 3000 ); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForDefault() { this.beforeTest(CosmosMetricCategory.fromString("DeFAult")); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(5); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForDefaultPlusDetails() { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.fromString("RequestDetails"), CosmosMetricCategory.fromString("OperationDETAILS")); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(7); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesInvalidCategory() { String badCategoryName = "InvalidCategory"; try { this.beforeTest( CosmosMetricCategory.DEFAULT, CosmosMetricCategory.fromString(badCategoryName)); fail("Should have thrown exception"); } catch (IllegalArgumentException argError) { assertThat(argError.getMessage()).contains(badCategoryName); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForAll() { this.beforeTest(CosmosMetricCategory.ALL); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(10); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectEndpoints)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.Legacy)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.AddressResolutions)).isEqualTo(true); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void endpointMetricsAreDurable() throws IllegalAccessException { this.beforeTest(CosmosMetricCategory.ALL); try { if (client.asyncClient().getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { return; } RntbdTransportClient transportClient = (RntbdTransportClient) ReflectionUtils.getTransportClient(client); RntbdServiceEndpoint.Provider endpointProvider = (RntbdServiceEndpoint.Provider) ReflectionUtils.getRntbdEndpointProvider(transportClient); ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor = ReflectionUtils.getProactiveOpenConnectionsProcessor(transportClient); AddressSelector addressSelector = (AddressSelector) FieldUtils.readField(transportClient, "addressSelector", true); String address = "https: RntbdEndpoint firstEndpoint = endpointProvider.createIfAbsent(URI.create(address), new Uri(address), proactiveOpenConnectionsProcessor, Configs.getMinConnectionPoolSizePerEndpoint(), addressSelector); RntbdDurableEndpointMetrics firstDurableMetricsInstance = firstEndpoint.durableEndpointMetrics(); firstEndpoint.close(); assertThat(firstEndpoint.durableEndpointMetrics().getEndpoint()).isNull(); RntbdEndpoint secondEndpoint = endpointProvider.createIfAbsent(URI.create(address), new Uri(address), proactiveOpenConnectionsProcessor, Configs.getMinConnectionPoolSizePerEndpoint(), addressSelector); assertThat(firstEndpoint).isNotSameAs(secondEndpoint); assertThat(firstDurableMetricsInstance).isSameAs(secondEndpoint.durableEndpointMetrics()); } finally { this.afterTest(); } } @Test(groups = { "fast" }, timeOut = TIMEOUT) public void effectiveMetricCategoriesForAllLatebound() { this.beforeTest(CosmosMetricCategory.DEFAULT); try { assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(5); EnumSet<MetricCategory> clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.OperationSummary)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectChannels)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.DirectRequests)).isEqualTo(true); assertThat(this.getEffectiveMetricCategories().contains(MetricCategory.System)).isEqualTo(true); this.inputMetricsOptions .setMetricCategories(CosmosMetricCategory.ALL) .removeMetricCategories(CosmosMetricCategory.OPERATION_DETAILS) .addMetricCategories(CosmosMetricCategory.OPERATION_DETAILS, CosmosMetricCategory.REQUEST_DETAILS) .configureDefaultPercentiles(0.9) .enableHistogramsByDefault(false) .setEnabled(true); assertThat(this.getEffectiveMetricCategories().size()).isEqualTo(10); clientMetricCategories = ImplementationBridgeHelpers .CosmosAsyncClientHelper .getCosmosAsyncClientAccessor() .getMetricCategories(client.asyncClient()); assertThat(clientMetricCategories).isEqualTo(this.getEffectiveMetricCategories()); } finally { this.afterTest(); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void invalidMeterNameThrows() { try { CosmosMetricName.fromString("InvalidMeterName"); fail("Should have thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("InvalidMeterName"); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void invalidMeterCategoryThrows() { try { CosmosMetricCategory.fromString("InvalidMeterCategory"); fail("Should have thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("InvalidMeterCategory"); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void invalidMeterTagNameThrows() { try { CosmosMetricTagName.fromString("InvalidMeterTagName"); fail("Should have thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).contains("InvalidMeterTagName"); } } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void meterTagNameFromStringConversion() { assertThat(CosmosMetricTagName.fromString("aLl ")) .isSameAs(CosmosMetricTagName.ALL); assertThat(CosmosMetricTagName.fromString("Default")) .isSameAs(CosmosMetricTagName.DEFAULT); assertThat(CosmosMetricTagName.fromString("minimum")) .isSameAs(CosmosMetricTagName.MINIMUM); assertThat(CosmosMetricTagName.fromString("IsForceCollectionRoutingMapRefresh")) .isSameAs(CosmosMetricTagName.ADDRESS_RESOLUTION_COLLECTION_MAP_REFRESH); assertThat(CosmosMetricTagName.fromString("isForcerefresh")) .isSameAs(CosmosMetricTagName.ADDRESS_RESOLUTION_FORCED_REFRESH); assertThat(CosmosMetricTagName.fromString("ClientCorrelationID")) .isSameAs(CosmosMetricTagName.CLIENT_CORRELATION_ID); assertThat(CosmosMetricTagName.fromString("container")) .isSameAs(CosmosMetricTagName.CONTAINER); assertThat(CosmosMetricTagName.fromString(" ConsistencyLevel")) .isSameAs(CosmosMetricTagName.CONSISTENCY_LEVEL); assertThat(CosmosMetricTagName.fromString("operation")) .isSameAs(CosmosMetricTagName.OPERATION); assertThat(CosmosMetricTagName.fromString("OperationStatusCode")) .isSameAs(CosmosMetricTagName.OPERATION_STATUS_CODE); assertThat(CosmosMetricTagName.fromString("PartitionKeyRangeId")) .isSameAs(CosmosMetricTagName.PARTITION_KEY_RANGE_ID); assertThat(CosmosMetricTagName.fromString("regionname")) .isSameAs(CosmosMetricTagName.REGION_NAME); assertThat(CosmosMetricTagName.fromString("RequestOperationType")) .isSameAs(CosmosMetricTagName.REQUEST_OPERATION_TYPE); assertThat(CosmosMetricTagName.fromString("requestStatusCode")) .isSameAs(CosmosMetricTagName.REQUEST_STATUS_CODE); assertThat(CosmosMetricTagName.fromString("serviceaddress")) .isSameAs(CosmosMetricTagName.SERVICE_ADDRESS); assertThat(CosmosMetricTagName.fromString("serviceEndpoint")) .isSameAs(CosmosMetricTagName.SERVICE_ENDPOINT); assertThat(CosmosMetricTagName.fromString("partitionID")) .isSameAs(CosmosMetricTagName.PARTITION_ID); assertThat(CosmosMetricTagName.fromString("REPLICAid")) .isSameAs(CosmosMetricTagName.REPLICA_ID); } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void meterCategoryFromStringConversion() { assertThat(CosmosMetricCategory.fromString("aLl ")) .isSameAs(CosmosMetricCategory.ALL); assertThat(CosmosMetricCategory.fromString("Default")) .isSameAs(CosmosMetricCategory.DEFAULT); assertThat(CosmosMetricCategory.fromString("minimum")) .isSameAs(CosmosMetricCategory.MINIMUM); assertThat(CosmosMetricCategory.fromString("operationsummary ")) .isSameAs(CosmosMetricCategory.OPERATION_SUMMARY); assertThat(CosmosMetricCategory.fromString("operationDetails")) .isSameAs(CosmosMetricCategory.OPERATION_DETAILS); assertThat(CosmosMetricCategory.fromString("RequestSummary")) .isSameAs(CosmosMetricCategory.REQUEST_SUMMARY); assertThat(CosmosMetricCategory.fromString("RequestDetails")) .isSameAs(CosmosMetricCategory.REQUEST_DETAILS); assertThat(CosmosMetricCategory.fromString("DirectChannels")) .isSameAs(CosmosMetricCategory.DIRECT_CHANNELS); assertThat(CosmosMetricCategory.fromString("DirectRequests")) .isSameAs(CosmosMetricCategory.DIRECT_REQUESTS); assertThat(CosmosMetricCategory.fromString("DirectEndpoints")) .isSameAs(CosmosMetricCategory.DIRECT_ENDPOINTS); assertThat(CosmosMetricCategory.fromString("DirectAddressResolutions")) .isSameAs(CosmosMetricCategory.DIRECT_ADDRESS_RESOLUTIONS); assertThat(CosmosMetricCategory.fromString("system")) .isSameAs(CosmosMetricCategory.SYSTEM); assertThat(CosmosMetricCategory.fromString("Legacy")) .isSameAs(CosmosMetricCategory.LEGACY); } @Test(groups = {"fast"}, timeOut = TIMEOUT) public void meterNameFromStringConversion() { assertThat(CosmosMetricName.fromString("cosmos.client.op.laTency")) .isSameAs(CosmosMetricName.OPERATION_SUMMARY_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.client.op.cAlls")) .isSameAs(CosmosMetricName.OPERATION_SUMMARY_CALLS); assertThat(CosmosMetricName.fromString("cosmos.client.op.rus")) .isSameAs(CosmosMetricName.OPERATION_SUMMARY_REQUEST_CHARGE); assertThat(CosmosMetricName.fromString("cosmos.client.OP.actualItemCount")) .isSameAs(CosmosMetricName.OPERATION_DETAILS_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.op.MAXItemCount")) .isSameAs(CosmosMetricName.OPERATION_DETAILS_MAX_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.op.REGIONScontacted")) .isSameAs(CosmosMetricName.OPERATION_DETAILS_REGIONS_CONTACTED); assertThat(CosmosMetricName.fromString("cosmos.client.req.reqPaylOADSize")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_SIZE_REQUEST); assertThat(CosmosMetricName.fromString("cosmos.client.req.rspPayloadSIZE")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_SIZE_RESPONSE); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.backendLatency")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_BACKEND_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.LAtency")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.RUS")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_REQUEST_CHARGE); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.rntbd.ReQUEsts")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_REQUESTS); assertThat(CosmosMetricName.fromString("cosmos.client.req.rntbd.TIMEline")) .isSameAs(CosmosMetricName.REQUEST_DETAILS_DIRECT_TIMELINE); assertThat(CosmosMetricName.fromString("cosmos.client.Req.rntbd.actualItemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.req.rntbd.actualITemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_DIRECT_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.gw.LAtency")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.gw.RUS")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_REQUEST_CHARGE); assertThat(CosmosMetricName.fromString("cosmos.CLIENT.req.gw.ReQUEsts")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_REQUESTS); assertThat(CosmosMetricName.fromString("cosmos.client.req.gw.tiMELine")) .isSameAs(CosmosMetricName.REQUEST_DETAILS_GATEWAY_TIMELINE); assertThat(CosmosMetricName.fromString("cosmos.client.Req.gw.actualItemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.req.gw.actualITemCount")) .isSameAs(CosmosMetricName.REQUEST_SUMMARY_GATEWAY_ACTUAL_ITEM_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.addressResolution.latency")) .isSameAs(CosmosMetricName.DIRECT_ADDRESS_RESOLUTION_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.addressResolution.requests")) .isSameAs(CosmosMetricName.DIRECT_ADDRESS_RESOLUTION_REQUESTS); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.channels.acquired.COUNT")) .isSameAs(CosmosMetricName.DIRECT_CHANNELS_ACQUIRED_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.channels.available.COUNT")) .isSameAs(CosmosMetricName.DIRECT_CHANNELS_AVAILABLE_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.channels.closed.COUNT")) .isSameAs(CosmosMetricName.DIRECT_CHANNELS_CLOSED_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.endpoints.COUNT")) .isSameAs(CosmosMetricName.DIRECT_ENDPOINTS_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.endpoints.evicted")) .isSameAs(CosmosMetricName.DIRECT_ENDPOINTS_EVICTED); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.concurrent.count")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_CONCURRENT_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.LAtency")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_LATENCY); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.FAIled.latency")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_LATENCY_FAILED); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.successful.latency")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_LATENCY_SUCCESS); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.requests.queued.count")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_QUEUED_COUNT); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.req.RSPsize")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_SIZE_RESPONSE); assertThat(CosmosMetricName.fromString("cosmos.client.RNTBD.req.reqsize")) .isSameAs(CosmosMetricName.DIRECT_REQUEST_SIZE_REQUEST); } @Test(groups = { "unit" }, timeOut = TIMEOUT) private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); return new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); } private void validateItemResponse(InternalObjectNode containerProperties, CosmosItemResponse<InternalObjectNode> createResponse) { assertThat(BridgeInternal.getProperties(createResponse).getId()).isNotNull(); assertThat(BridgeInternal.getProperties(createResponse).getId()) .as("check Resource Id") .isEqualTo(containerProperties.getId()); } private void validateReadManyFeedResponse( List<InternalObjectNode> createdDocs, FeedResponse<InternalObjectNode> readManyResponse) { assertThat(readManyResponse).isNotNull(); assertThat(readManyResponse.getResults()).isNotNull(); List<InternalObjectNode> docsFromResponse = readManyResponse.getResults(); assertThat(docsFromResponse).hasSize(createdDocs.size()); for (InternalObjectNode doc: createdDocs) { assertThat(docsFromResponse.stream().anyMatch(r -> r.getId() != null && r.getId().equals(doc.getId()))); } } private void validateItemCountMetrics(Tag expectedOperationTag) { if (this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)) { this.assertMetrics("cosmos.client.op.maxItemCount", true, expectedOperationTag); this.assertMetrics("cosmos.client.op.actualItemCount", true, expectedOperationTag); } } private void validateRequestActualItemCountMetrics(Tag... expectedRequestTags) { if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)) { if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() == ConnectionMode.DIRECT) { for (Tag expectedRequestTag : expectedRequestTags) { this.assertMetrics("cosmos.client.req.rntbd.actualItemCount", true, expectedRequestTag); } } else { for (Tag expectedRequestTag : expectedRequestTags) { this.assertMetrics("cosmos.client.req.gw.actualItemCount", true, expectedRequestTag); } } } } private void validateReasonableRUs(Meter reportedRequestChargeMeter, int expectedMinRu, int expectedMaxRu) { List<Measurement> measurements = new ArrayList<>(); reportedRequestChargeMeter.measure().forEach(measurements::add); logger.info("RequestedRequestChargeMeter: {} {}", reportedRequestChargeMeter, reportedRequestChargeMeter.getId()); assertThat(measurements.size()).isGreaterThan(0); for (int i = 0; i < measurements.size(); i++) { assertThat(measurements.get(i).getValue()).isGreaterThanOrEqualTo(expectedMinRu); assertThat(measurements.get(i).getValue()).isLessThanOrEqualTo(expectedMaxRu); } } private void validateMetrics(Tag expectedOperationTag, Tag expectedRequestTag, int minRu, int maxRu) { this.assertMetrics("cosmos.client.op.latency", true, expectedOperationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedOperationTag); if (expectedOperationTag.getKey() == "OperationStatusCode" && ("200".equals(expectedOperationTag.getValue()) || "201".equals(expectedOperationTag.getValue()))) { Tag expectedSubStatusCodeOperationTag = Tag.of(TagName.OperationSubStatusCode.toString(), "0"); this.assertMetrics("cosmos.client.op.latency", true, expectedSubStatusCodeOperationTag); this.assertMetrics("cosmos.client.op.calls", true, expectedSubStatusCodeOperationTag); } Meter reportedOpRequestCharge = this.assertMetrics( "cosmos.client.op.RUs", true, expectedOperationTag); validateReasonableRUs(reportedOpRequestCharge, minRu, maxRu); if (this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)) { this.assertMetrics("cosmos.client.op.regionsContacted", true, expectedOperationTag); this.assertMetrics( "cosmos.client.op.regionsContacted", true, Tag.of(TagName.RegionName.toString(), this.preferredRegion.toLowerCase(Locale.ROOT))); } if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestSummary)) { this.assertMetrics( "cosmos.client.req.reqPayloadSize", true, expectedOperationTag); this.assertMetrics( "cosmos.client.req.rspPayloadSize", true, expectedOperationTag); } if (this.client.asyncClient().getConnectionPolicy().getConnectionMode() == ConnectionMode.DIRECT) { this.assertMetrics("cosmos.client.req.rntbd.latency", true, expectedRequestTag); this.assertMetrics( "cosmos.client.req.rntbd.latency", true, Tag.of(TagName.RegionName.toString(), this.preferredRegion.toLowerCase(Locale.ROOT))); this.assertMetrics("cosmos.client.req.rntbd.backendLatency", true, expectedRequestTag); this.assertMetrics("cosmos.client.req.rntbd.requests", true, expectedRequestTag); Meter reportedRntbdRequestCharge = this.assertMetrics("cosmos.client.req.rntbd.RUs", true, expectedRequestTag); validateReasonableRUs(reportedRntbdRequestCharge, minRu, maxRu); if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)) { this.assertMetrics("cosmos.client.req.rntbd.timeline", true, expectedRequestTag); } } else { this.assertMetrics("cosmos.client.req.gw.latency", true, expectedRequestTag); if (this.getEffectiveMetricCategories().contains(MetricCategory.OperationDetails)) { this.assertMetrics( "cosmos.client.req.gw.latency", true, Tag.of(TagName.RegionName.toString(), this.preferredRegion.toLowerCase(Locale.ROOT))); } this.assertMetrics("cosmos.client.req.gw.backendLatency", false, expectedRequestTag); this.assertMetrics("cosmos.client.req.gw.requests", true, expectedRequestTag); Meter reportedGatewayRequestCharge = this.assertMetrics("cosmos.client.req.gw.RUs", true, expectedRequestTag); validateReasonableRUs(reportedGatewayRequestCharge, minRu, maxRu); if (this.getEffectiveMetricCategories().contains(MetricCategory.RequestDetails)) { this.assertMetrics("cosmos.client.req.gw.timeline", true, expectedRequestTag); } } } private Meter assertMetrics(String prefix, boolean expectedToFind) { return assertMetrics(prefix, expectedToFind, null); } private Meter assertMetrics(String prefix, boolean expectedToFind, Tag withTag) { assertThat(this.meterRegistry).isNotNull(); assertThat(this.meterRegistry.getMeters()).isNotNull(); List<Meter> meters = this.meterRegistry.getMeters().stream().collect(Collectors.toList()); if (expectedToFind) { assertThat(meters.size()).isGreaterThan(0); assertTagInAllMeters(meters, prefix); } List<Meter> meterPrefixMatches = meters .stream() .filter(meter -> meter.getId().getName().startsWith(prefix)) .collect(Collectors.toList()); List<Meter> meterMatches = meterPrefixMatches .stream() .filter(meter -> (withTag == null || meter.getId().getTags().contains(withTag)) && meter.measure().iterator().next().getValue() > 0) .collect(Collectors.toList()); if (expectedToFind) { if (meterMatches.size() == 0) { String message = String.format( "No meter found for the expected constraints - prefix '%s', withTag '%s'", prefix, withTag); logger.error(message); logger.info("Meters matching the prefix"); meterPrefixMatches.forEach(meter -> logger.info("{} has measurements {}", meter.getId(), meter.measure().iterator().hasNext())); fail(message); } if (meterMatches.size() > 1) { StringBuilder sb = new StringBuilder(); final AtomicReference<Meter> exactMatchMeter = new AtomicReference<>(null); meterMatches.forEach(m -> { if (exactMatchMeter.get() == null && m.getId().getName().equals(prefix)) { exactMatchMeter.set(m); } String message = String.format( "Found more than one meter '%s' for prefix '%s' withTag '%s' --> '%s'", m.getId(), prefix, withTag, m); sb.append(message); sb.append(System.getProperty("line.separator")); logger.info(message); }); if (exactMatchMeter.get() != null) { logger.info("Found exact match {}", exactMatchMeter); return exactMatchMeter.get(); } } return meterMatches.get(0); } else { if (meterMatches.size() > 0) { StringBuilder sb = new StringBuilder(); meterMatches.forEach(m -> { String message = String.format( "Found unexpected meter '%s' for prefix '%s' withTag '%s' --> '%s'", m, prefix, withTag, m); sb.append(message); sb.append(System.getProperty("line.separator")); logger.error(message); }); fail(sb.toString()); } assertThat(meterMatches.size()).isEqualTo(0); return null; } } private void assertTagInAllMeters(List<Meter> meters, String prefix) { List<Meter> meterMatches = meters .stream() .filter(meter -> meter.getId().getName().equals(prefix) && meter.getId().getTags().contains(this.clientCorrelationTag)) .collect(Collectors.toList()); if (meterMatches.size() > 0) { Set<String> possibleTags = new HashSet<>(); for (Tag tag : meterMatches.get(0).getId().getTags()) { possibleTags.add(tag.getKey()); } List<Meter> metersTagPresent = meterMatches .stream() .filter(meter -> { int numTags = 0; for (Tag tag : meter.getId().getTags()) { if (!possibleTags.contains(tag.getKey())) { return false; } numTags++; } return numTags == possibleTags.size(); } ) .collect(Collectors.toList()); if (metersTagPresent.size() != meterMatches.size()) { logger.error("MetersTagPresent"); for (Meter meter : metersTagPresent) { logger.error("Meter: {}", meter.getId()); } logger.error("MeterMatches"); for (Meter meter : meterMatches) { logger.error("Meter: {}", meter.getId()); } } assertThat(metersTagPresent.size()).isEqualTo(meterMatches.size()); } } private List<String> getAvailableWriteRegionNames(RxDocumentClientImpl rxDocumentClient) { try { 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 availableWriteLocations = DatabaseAccountLocationsInfoClass.getDeclaredField( "availableWriteLocations"); availableWriteLocations.setAccessible(true); @SuppressWarnings("unchecked") List<String> list = (List<String>) availableWriteLocations.get(locationInfo); return list; } catch (Exception error) { fail(error.toString()); return null; } } }
More information about `Schedulers.boundedElastic()`: https://projectreactor.io/docs/core/release/reference/#schedulers > ![image](https://github.com/user-attachments/assets/908ac3a4-063b-4dd3-962c-e247073393df)
private TokenCredential createAzurePipelinesCredential() { Configuration config = Configuration.getGlobalConfiguration(); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (hasText(serviceConnectionId) && hasText(clientId) && hasText(tenantId) && hasText(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); return request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic()); } return null; }
return request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic());
private TokenCredential createAzurePipelinesCredential() { Configuration config = Configuration.getGlobalConfiguration(); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (hasText(serviceConnectionId) && hasText(clientId) && hasText(tenantId) && hasText(systemAccessToken)) { AzurePipelinesCredential pipelinesCredential = new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build(); return request -> pipelinesCredential.getToken(request).subscribeOn(Schedulers.boundedElastic()); } return null; }
class ApplicationConfiguration { @Bean(name = DEFAULT_TOKEN_CREDENTIAL_BEAN_NAME) TokenCredential tokenCredential() { ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); TokenCredential createAzurePipelinesCredential = createAzurePipelinesCredential(); if (createAzurePipelinesCredential != null) { builder.addLast(createAzurePipelinesCredential); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
class ApplicationConfiguration { @Bean(name = DEFAULT_TOKEN_CREDENTIAL_BEAN_NAME) TokenCredential tokenCredential() { ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); TokenCredential createAzurePipelinesCredential = createAzurePipelinesCredential(); if (createAzurePipelinesCredential != null) { builder.addLast(createAzurePipelinesCredential); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
Can we either have a parameterless ctor for `ImdsRetryStrategy` that defaults to 5, or make this a constant with a comment somewhere so we know why it is 5?
HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryPolicy retryPolicy = options.getRetryPolicy(); if (retryPolicy == null && options.getUseImdsRetryStrategy()) { retryPolicy = new RetryPolicy(new ImdsRetryStrategy(5)); } policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); }
retryPolicy = new RetryPolicy(new ImdsRetryStrategy(5));
HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); HttpLogOptions httpLogOptions = (options.getHttpLogOptions() == null) ? new HttpLogOptions() : options.getHttpLogOptions(); ClientOptions localClientOptions = options.getClientOptions() != null ? options.getClientOptions() : DEFAULT_CLIENT_OPTIONS; userAgent = UserAgentUtil.toUserAgentString(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); List<HttpHeader> httpHeaderList = new ArrayList<>(); localClientOptions.getHeaders().forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); policies.addAll(options.getPerCallPolicies()); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryPolicy retryPolicy = options.getRetryPolicy(); if (retryPolicy == null && options.getUseImdsRetryStrategy()) { retryPolicy = new RetryPolicy(new ImdsRetryStrategy()); } policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, options.getRetryOptions())); policies.addAll(options.getPerRetryPolicies()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .clientOptions(localClientOptions) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { byte[] certificateBytes = getCertificateBytes(); if (CertificateUtil.isPem(certificateBytes)) { List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(certificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(certificateBytes); 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); if (accessToken.getRefreshAt() != null) { result.setRefreshInSeconds(accessToken.getRefreshAt().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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); options.setUseImdsRetryStrategy(); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); void initializeHttpPipelineAdapter() { if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(getPipeline(), options); } } HttpPipeline getPipeline() { if (this.httpPipeline != null) { return httpPipeline; } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; return this.httpPipeline; } HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient != null ? httpClient : HttpClient.createDefault()); return this.httpPipeline; } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final Pattern WINDOWS_PROCESS_ERROR_MESSAGE = Pattern.compile("'azd?' is not recognized"); static final Pattern SH_PROCESS_ERROR_MESSAGE = Pattern.compile("azd?:.*not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private final Map<String, String> properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final byte[] certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; private Class<?> interactiveBrowserBroker; private Method getMsalRuntimeBroker; HttpPipeline httpPipeline; /** * 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. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, Function<HttpPipeline, String> clientAssertionSupplierWithHttpPipeline, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } 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.clientAssertionSupplierWithHttpPipeline = clientAssertionSupplierWithHttpPipeline; this.options = options; } ConfidentialClientApplication getConfidentialClient(boolean enableCae) { 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; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { byte[] certificateBytes = getCertificateBytes(); if (CertificateUtil.isPem(certificateBytes)) { List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(certificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(certificateBytes); 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) { throw 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 if (clientAssertionSupplierWithHttpPipeline != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); } else { throw 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 .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); applicationBuilder.clientCapabilities(set); } 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(enableCae) .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw 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(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential, boolean enableCae) { 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 builder = PublicClientApplication.builder(clientId); try { builder = builder .logPii(options.isUnsafeSupportLoggingEnabled()) .authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (enableCae) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } if (options.isBrokerEnabled()) { if (interactiveBrowserBroker == null) { try { interactiveBrowserBroker = Class.forName("com.azure.identity.broker.implementation.InteractiveBrowserBroker"); } catch (ClassNotFoundException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not load the brokered authentication library. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } getMsalRuntimeBroker = null; try { getMsalRuntimeBroker = interactiveBrowserBroker.getMethod("getMsalRuntimeBroker"); } catch (NoSuchMethodException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the InteractiveBrowserBroker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } try { if (getMsalRuntimeBroker != null) { builder.broker((IBroker) getMsalRuntimeBroker.invoke(null)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not obtain the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", null)); } } catch (InvocationTargetException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new IllegalStateException("Could not invoke the MSAL Broker. " + "Ensure that the azure-identity-broker library is on the classpath.", e)); } } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl(enableCae) .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(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { 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); applicationBuilder .instanceDiscovery(false) .validateAuthority(false) .logPii(options.isUnsafeSupportLoggingEnabled()); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw 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()); if (accessToken.getRefreshAt() != null) { result.setRefreshInSeconds(accessToken.getRefreshAt().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()); } return applicationBuilder.build(); } ManagedIdentityApplication getManagedIdentityMsalApplication() { ManagedIdentityId managedIdentityId = CoreUtils.isNullOrEmpty(clientId) ? (CoreUtils.isNullOrEmpty(resourceId) ? ManagedIdentityId.systemAssigned() : ManagedIdentityId.userAssignedResourceId(resourceId)) : ManagedIdentityId.userAssignedClientId(clientId); ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication .builder(managedIdentityId) .logPii(options.isUnsafeSupportLoggingEnabled()); if ("DEFAULT_TO_IMDS".equals(String.valueOf(ManagedIdentityApplication.getManagedIdentitySource()))) { options.setUseImdsRetryStrategy(); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { miBuilder.httpClient(httpPipelineAdapter); } else { miBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { miBuilder.executorService(options.getExecutorService()); } return miBuilder.build(); } ConfidentialClientApplication getWorkloadIdentityConfidentialClient() { 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) .logPii(options.isUnsafeSupportLoggingEnabled()) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (!options.isInstanceDiscoveryEnabled()) { LOGGER.log(LogLevel.VERBOSE, () -> "Instance discovery and authority validation is disabled. In this" + " state, the library will not fetch metadata to validate the specified authority host. As a" + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); } } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.appTokenProvider(getWorkloadIdentityTokenProvider()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } abstract Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider(); DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { 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 parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { OnBehalfOfParameters.OnBehalfOfParametersBuilder builder = OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder.build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); } if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); } builder.systemBrowserOptions(browserOptionsBuilder.build()); } if (options.isBrokerEnabled()) { builder.windowHandle(options.getBrokerWindowHandle()); if (options.isMsaPassthroughEnabled()) { Map<String, String> extraQueryParameters = new HashMap<>(); extraQueryParameters.put("msal_request_type", "consumer_passthrough"); builder.extraQueryParameters(extraQueryParameters); } } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { 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()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { 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(this.options.getCredentialProcessTimeout().getSeconds(), 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."); try (JsonReader reader = JsonProviders.createReader(processOutput)) { AzureCliToken tokenHolder = AzureCliToken.fromJson(reader); String accessToken = tokenHolder.getAccessToken(); OffsetDateTime tokenExpiration = tokenHolder.getTokenExpiration(); token = new AccessToken(accessToken, tokenExpiration); } } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken getTokenFromAzureDeveloperCLIAuthentication(StringBuilder azdCommand) { 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, azdCommand.toString()); builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); 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 Azure Developer CLI command from.")); } 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 (WINDOWS_PROCESS_ERROR_MESSAGE.matcher(line).find() || SH_PROCESS_ERROR_MESSAGE.matcher(line).find()) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable. Azure Developer 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(this.options.getCredentialProcessTimeout().getSeconds(), TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("azd auth login") || redactedOutput.contains("not logged in")) { throw LoggingUtil.logCredentialUnavailableException( LOGGER, options, new CredentialUnavailableException( "AzureDeveloperCliCredential authentication unavailable." + " Please run 'azd auth login' to set up account.")); } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure Developer CLI ", null)); } } LOGGER.verbose( "Azure Developer CLI Authentication => A token response was received from Azure Developer CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize( processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("token"); String time = objectMap.get("expiresOn"); String standardTime = time.substring(0, time.indexOf("Z")); OffsetDateTime expiresOn = LocalDateTime .parse(standardTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.of("Z")) .toOffsetDateTime() .withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { IllegalStateException ex = new IllegalStateException(redactInfo(e.getMessage())); ex.setStackTrace(e.getStackTrace()); throw LOGGER.logExceptionAsError(ex); } return token; } AccessToken authenticateWithExchangeTokenHelper(TokenRequestContext request, String assertionToken) throws IOException { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; String urlParams = "client_assertion=" + assertionToken + "&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_id=" + clientId + "&grant_type=client_credentials&scope=" + urlEncode(request.getScopes().get(0)); 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.setRequestProperty("User-Agent", userAgent); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); void initializeHttpPipelineAdapter() { if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(getPipeline(), options); } } HttpPipeline getPipeline() { if (this.httpPipeline != null) { return httpPipeline; } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { this.httpPipeline = httpPipeline; return this.httpPipeline; } HttpClient httpClient = options.getHttpClient(); this.httpPipeline = setupPipeline(httpClient != null ? httpClient : HttpClient.createDefault()); return this.httpPipeline; } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { return certificate; } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return new ByteArrayInputStream(certificate); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } static String urlEncode(String value) throws IOException { return URLEncoder.encode(value, StandardCharsets.UTF_8.name()); } static URL getUrl(String uri) throws MalformedURLException { return new URL(uri); } /** * 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; } }
Doesn't `retries-1` just end up being `retryAttempts`?
public Duration calculateRetryDelay(int retryAttempts) { long retries = retryAttempts + 1; long delay = (long) (baseDelay.toMillis() * Math.pow(2, retries - 1)); return Duration.ofMillis(delay); }
long delay = (long) (baseDelay.toMillis() * Math.pow(2, retries - 1));
public Duration calculateRetryDelay(int retryAttempts) { long delay = (long) (baseDelay.toMillis() * Math.pow(2, retryAttempts)); return Duration.ofMillis(delay); }
class ImdsRetryStrategy implements RetryStrategy { private static final ClientLogger LOGGER = new ClientLogger(ImdsRetryStrategy.class); private final int maxRetries; private final Duration baseDelay; private final Predicate<RequestRetryCondition> shouldRetryCondition; public ImdsRetryStrategy(int maxRetries) { this(maxRetries, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries, Duration baseDelay) { this.maxRetries = maxRetries; this.baseDelay = baseDelay; this.shouldRetryCondition = this::defaultShouldRetryCondition; } @Override public int getMaxRetries() { return maxRetries; } @Override @Override public boolean shouldRetryCondition(RequestRetryCondition requestRetryCondition) { return this.shouldRetryCondition.test(requestRetryCondition); } private boolean defaultShouldRetryCondition(RequestRetryCondition condition) { HttpResponse response = condition.getResponse(); Throwable throwable = condition.getThrowable(); if (response != null) { int statusCode = response.getStatusCode(); if (statusCode == 400) { return false; } if (statusCode == 403) { return response.getHeaderValue("ResponseMessage").contains("A socket operation was attempted to an unreachable network"); } if (statusCode == 410 || statusCode == 429 || statusCode == 404 || (statusCode >= 500 && statusCode <= 599)) { return true; } } if (throwable instanceof IOException) { return true; } return false; } }
class ImdsRetryStrategy implements RetryStrategy { private static final int MAX_RETRIES = 5; private final int maxRetries; private final Duration baseDelay; private final Predicate<RequestRetryCondition> shouldRetryCondition; public ImdsRetryStrategy() { this(MAX_RETRIES, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries) { this(maxRetries, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries, Duration baseDelay) { this.maxRetries = maxRetries; this.baseDelay = baseDelay; this.shouldRetryCondition = this::defaultShouldRetryCondition; } @Override public int getMaxRetries() { return maxRetries; } @Override @Override public boolean shouldRetryCondition(RequestRetryCondition requestRetryCondition) { return this.shouldRetryCondition.test(requestRetryCondition); } @Override public boolean shouldRetry(HttpResponse httpResponse) { if (httpResponse != null) { int statusCode = httpResponse.getStatusCode(); if (statusCode == 400) { return false; } if (statusCode == 403) { return httpResponse.getHeaderValue("ResponseMessage").contains("A socket operation was attempted to an unreachable network"); } if (statusCode == 410 || statusCode == 429 || statusCode == 404 || (statusCode >= 500 && statusCode <= 599)) { return true; } } return false; } @Override public boolean shouldRetryException(Throwable throwable) { return throwable instanceof IOException; } private boolean defaultShouldRetryCondition(RequestRetryCondition condition) { HttpResponse response = condition.getResponse(); Throwable throwable = condition.getThrowable(); if (response != null) { return shouldRetry(response); } return shouldRetryException(throwable); } }
Should we check this first? Will we ever get both a `response` and a `throwable`?
private boolean defaultShouldRetryCondition(RequestRetryCondition condition) { HttpResponse response = condition.getResponse(); Throwable throwable = condition.getThrowable(); if (response != null) { int statusCode = response.getStatusCode(); if (statusCode == 400) { return false; } if (statusCode == 403) { return response.getHeaderValue("ResponseMessage").contains("A socket operation was attempted to an unreachable network"); } if (statusCode == 410 || statusCode == 429 || statusCode == 404 || (statusCode >= 500 && statusCode <= 599)) { return true; } } if (throwable instanceof IOException) { return true; } return false; }
if (throwable instanceof IOException) {
private boolean defaultShouldRetryCondition(RequestRetryCondition condition) { HttpResponse response = condition.getResponse(); Throwable throwable = condition.getThrowable(); if (response != null) { return shouldRetry(response); } return shouldRetryException(throwable); }
class ImdsRetryStrategy implements RetryStrategy { private static final ClientLogger LOGGER = new ClientLogger(ImdsRetryStrategy.class); private final int maxRetries; private final Duration baseDelay; private final Predicate<RequestRetryCondition> shouldRetryCondition; public ImdsRetryStrategy(int maxRetries) { this(maxRetries, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries, Duration baseDelay) { this.maxRetries = maxRetries; this.baseDelay = baseDelay; this.shouldRetryCondition = this::defaultShouldRetryCondition; } @Override public int getMaxRetries() { return maxRetries; } @Override public Duration calculateRetryDelay(int retryAttempts) { long retries = retryAttempts + 1; long delay = (long) (baseDelay.toMillis() * Math.pow(2, retries - 1)); return Duration.ofMillis(delay); } @Override public boolean shouldRetryCondition(RequestRetryCondition requestRetryCondition) { return this.shouldRetryCondition.test(requestRetryCondition); } }
class ImdsRetryStrategy implements RetryStrategy { private static final int MAX_RETRIES = 5; private final int maxRetries; private final Duration baseDelay; private final Predicate<RequestRetryCondition> shouldRetryCondition; public ImdsRetryStrategy() { this(MAX_RETRIES, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries) { this(maxRetries, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries, Duration baseDelay) { this.maxRetries = maxRetries; this.baseDelay = baseDelay; this.shouldRetryCondition = this::defaultShouldRetryCondition; } @Override public int getMaxRetries() { return maxRetries; } @Override public Duration calculateRetryDelay(int retryAttempts) { long delay = (long) (baseDelay.toMillis() * Math.pow(2, retryAttempts)); return Duration.ofMillis(delay); } @Override public boolean shouldRetryCondition(RequestRetryCondition requestRetryCondition) { return this.shouldRetryCondition.test(requestRetryCondition); } @Override public boolean shouldRetry(HttpResponse httpResponse) { if (httpResponse != null) { int statusCode = httpResponse.getStatusCode(); if (statusCode == 400) { return false; } if (statusCode == 403) { return httpResponse.getHeaderValue("ResponseMessage").contains("A socket operation was attempted to an unreachable network"); } if (statusCode == 410 || statusCode == 429 || statusCode == 404 || (statusCode >= 500 && statusCode <= 599)) { return true; } } return false; } @Override public boolean shouldRetryException(Throwable throwable) { return throwable instanceof IOException; } }
instanceof will take care of it if its null
private boolean defaultShouldRetryCondition(RequestRetryCondition condition) { HttpResponse response = condition.getResponse(); Throwable throwable = condition.getThrowable(); if (response != null) { int statusCode = response.getStatusCode(); if (statusCode == 400) { return false; } if (statusCode == 403) { return response.getHeaderValue("ResponseMessage").contains("A socket operation was attempted to an unreachable network"); } if (statusCode == 410 || statusCode == 429 || statusCode == 404 || (statusCode >= 500 && statusCode <= 599)) { return true; } } if (throwable instanceof IOException) { return true; } return false; }
if (throwable instanceof IOException) {
private boolean defaultShouldRetryCondition(RequestRetryCondition condition) { HttpResponse response = condition.getResponse(); Throwable throwable = condition.getThrowable(); if (response != null) { return shouldRetry(response); } return shouldRetryException(throwable); }
class ImdsRetryStrategy implements RetryStrategy { private static final ClientLogger LOGGER = new ClientLogger(ImdsRetryStrategy.class); private final int maxRetries; private final Duration baseDelay; private final Predicate<RequestRetryCondition> shouldRetryCondition; public ImdsRetryStrategy(int maxRetries) { this(maxRetries, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries, Duration baseDelay) { this.maxRetries = maxRetries; this.baseDelay = baseDelay; this.shouldRetryCondition = this::defaultShouldRetryCondition; } @Override public int getMaxRetries() { return maxRetries; } @Override public Duration calculateRetryDelay(int retryAttempts) { long retries = retryAttempts + 1; long delay = (long) (baseDelay.toMillis() * Math.pow(2, retries - 1)); return Duration.ofMillis(delay); } @Override public boolean shouldRetryCondition(RequestRetryCondition requestRetryCondition) { return this.shouldRetryCondition.test(requestRetryCondition); } }
class ImdsRetryStrategy implements RetryStrategy { private static final int MAX_RETRIES = 5; private final int maxRetries; private final Duration baseDelay; private final Predicate<RequestRetryCondition> shouldRetryCondition; public ImdsRetryStrategy() { this(MAX_RETRIES, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries) { this(maxRetries, Duration.ofMillis(800)); } public ImdsRetryStrategy(int maxRetries, Duration baseDelay) { this.maxRetries = maxRetries; this.baseDelay = baseDelay; this.shouldRetryCondition = this::defaultShouldRetryCondition; } @Override public int getMaxRetries() { return maxRetries; } @Override public Duration calculateRetryDelay(int retryAttempts) { long delay = (long) (baseDelay.toMillis() * Math.pow(2, retryAttempts)); return Duration.ofMillis(delay); } @Override public boolean shouldRetryCondition(RequestRetryCondition requestRetryCondition) { return this.shouldRetryCondition.test(requestRetryCondition); } @Override public boolean shouldRetry(HttpResponse httpResponse) { if (httpResponse != null) { int statusCode = httpResponse.getStatusCode(); if (statusCode == 400) { return false; } if (statusCode == 403) { return httpResponse.getHeaderValue("ResponseMessage").contains("A socket operation was attempted to an unreachable network"); } if (statusCode == 410 || statusCode == 429 || statusCode == 404 || (statusCode >= 500 && statusCode <= 599)) { return true; } } return false; } @Override public boolean shouldRetryException(Throwable throwable) { return throwable instanceof IOException; } }
```suggestion "Imds Retry Strategy should retry on 599 status response."); ```
public void testShouldRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); HttpResponse httpResponse = new MockHttpResponse(null, 400); Assertions.assertFalse(imdsRetryStrategy.shouldRetry(httpResponse), "Imds Retry Strategy should not retry on 400 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 410)), "Imds Retry Strategy should retry on 410 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 429)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 500)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 599)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 404)), "Imds Retry Strategy should retry on 429 status response."); }
"Imds Retry Strategy should retry on 429 status response.");
public void testShouldRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); HttpResponse httpResponse = new MockHttpResponse(null, 400); Assertions.assertFalse(imdsRetryStrategy.shouldRetry(httpResponse), "Imds Retry Strategy should not retry on 400 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 410)), "Imds Retry Strategy should retry on 410 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 429)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 500)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 599)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 404)), "Imds Retry Strategy should retry on 429 status response."); }
class ImdsRetryStrategyTest { @Test public void testIMDSRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); int retry = 0; Queue<Long> expectedEntries = new LinkedList<>(); expectedEntries.addAll(Arrays.asList(800L, 1600L, 3200L, 6400L, 12800L)); while (retry < imdsRetryStrategy.getMaxRetries()) { long timeout = (imdsRetryStrategy.calculateRetryDelay(retry).toMillis()); if (expectedEntries.contains(timeout)) { expectedEntries.remove(timeout); } else { Assertions.fail("Unexpected timeout: " + timeout); } retry++; } } @Test @Test public void testShouldRetryOnException() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); Assertions.assertFalse(imdsRetryStrategy.shouldRetryException(new Exception("Test Error")), "Imds Retry Strategy should not retry on general exception."); Assertions.assertTrue(imdsRetryStrategy.shouldRetryException(new IOException("Test Error")), "Imds Retry Strategy should retry on IOException."); } }
class ImdsRetryStrategyTest { @Test public void testIMDSRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); int retry = 0; Queue<Long> expectedEntries = new LinkedList<>(); expectedEntries.addAll(Arrays.asList(800L, 1600L, 3200L, 6400L, 12800L)); while (retry < imdsRetryStrategy.getMaxRetries()) { long timeout = (imdsRetryStrategy.calculateRetryDelay(retry).toMillis()); if (expectedEntries.contains(timeout)) { expectedEntries.remove(timeout); } else { Assertions.fail("Unexpected timeout: " + timeout); } retry++; } } @Test @Test public void testShouldRetryOnException() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); Assertions.assertFalse(imdsRetryStrategy.shouldRetryException(new Exception("Test Error")), "Imds Retry Strategy should not retry on general exception."); Assertions.assertTrue(imdsRetryStrategy.shouldRetryException(new IOException("Test Error")), "Imds Retry Strategy should retry on IOException."); } }
```suggestion "Imds Retry Strategy should retry on 404 status response."); ```
public void testShouldRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); HttpResponse httpResponse = new MockHttpResponse(null, 400); Assertions.assertFalse(imdsRetryStrategy.shouldRetry(httpResponse), "Imds Retry Strategy should not retry on 400 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 410)), "Imds Retry Strategy should retry on 410 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 429)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 500)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 599)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 404)), "Imds Retry Strategy should retry on 429 status response."); }
"Imds Retry Strategy should retry on 429 status response.");
public void testShouldRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); HttpResponse httpResponse = new MockHttpResponse(null, 400); Assertions.assertFalse(imdsRetryStrategy.shouldRetry(httpResponse), "Imds Retry Strategy should not retry on 400 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 410)), "Imds Retry Strategy should retry on 410 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 429)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 500)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 599)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 404)), "Imds Retry Strategy should retry on 429 status response."); }
class ImdsRetryStrategyTest { @Test public void testIMDSRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); int retry = 0; Queue<Long> expectedEntries = new LinkedList<>(); expectedEntries.addAll(Arrays.asList(800L, 1600L, 3200L, 6400L, 12800L)); while (retry < imdsRetryStrategy.getMaxRetries()) { long timeout = (imdsRetryStrategy.calculateRetryDelay(retry).toMillis()); if (expectedEntries.contains(timeout)) { expectedEntries.remove(timeout); } else { Assertions.fail("Unexpected timeout: " + timeout); } retry++; } } @Test @Test public void testShouldRetryOnException() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); Assertions.assertFalse(imdsRetryStrategy.shouldRetryException(new Exception("Test Error")), "Imds Retry Strategy should not retry on general exception."); Assertions.assertTrue(imdsRetryStrategy.shouldRetryException(new IOException("Test Error")), "Imds Retry Strategy should retry on IOException."); } }
class ImdsRetryStrategyTest { @Test public void testIMDSRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); int retry = 0; Queue<Long> expectedEntries = new LinkedList<>(); expectedEntries.addAll(Arrays.asList(800L, 1600L, 3200L, 6400L, 12800L)); while (retry < imdsRetryStrategy.getMaxRetries()) { long timeout = (imdsRetryStrategy.calculateRetryDelay(retry).toMillis()); if (expectedEntries.contains(timeout)) { expectedEntries.remove(timeout); } else { Assertions.fail("Unexpected timeout: " + timeout); } retry++; } } @Test @Test public void testShouldRetryOnException() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); Assertions.assertFalse(imdsRetryStrategy.shouldRetryException(new Exception("Test Error")), "Imds Retry Strategy should not retry on general exception."); Assertions.assertTrue(imdsRetryStrategy.shouldRetryException(new IOException("Test Error")), "Imds Retry Strategy should retry on IOException."); } }
```suggestion "Imds Retry Strategy should retry on 500 status response."); ```
public void testShouldRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); HttpResponse httpResponse = new MockHttpResponse(null, 400); Assertions.assertFalse(imdsRetryStrategy.shouldRetry(httpResponse), "Imds Retry Strategy should not retry on 400 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 410)), "Imds Retry Strategy should retry on 410 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 429)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 500)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 599)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 404)), "Imds Retry Strategy should retry on 429 status response."); }
"Imds Retry Strategy should retry on 429 status response.");
public void testShouldRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); HttpResponse httpResponse = new MockHttpResponse(null, 400); Assertions.assertFalse(imdsRetryStrategy.shouldRetry(httpResponse), "Imds Retry Strategy should not retry on 400 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 410)), "Imds Retry Strategy should retry on 410 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 429)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 500)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 599)), "Imds Retry Strategy should retry on 429 status response."); Assertions.assertTrue(imdsRetryStrategy.shouldRetry(new MockHttpResponse(null, 404)), "Imds Retry Strategy should retry on 429 status response."); }
class ImdsRetryStrategyTest { @Test public void testIMDSRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); int retry = 0; Queue<Long> expectedEntries = new LinkedList<>(); expectedEntries.addAll(Arrays.asList(800L, 1600L, 3200L, 6400L, 12800L)); while (retry < imdsRetryStrategy.getMaxRetries()) { long timeout = (imdsRetryStrategy.calculateRetryDelay(retry).toMillis()); if (expectedEntries.contains(timeout)) { expectedEntries.remove(timeout); } else { Assertions.fail("Unexpected timeout: " + timeout); } retry++; } } @Test @Test public void testShouldRetryOnException() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); Assertions.assertFalse(imdsRetryStrategy.shouldRetryException(new Exception("Test Error")), "Imds Retry Strategy should not retry on general exception."); Assertions.assertTrue(imdsRetryStrategy.shouldRetryException(new IOException("Test Error")), "Imds Retry Strategy should retry on IOException."); } }
class ImdsRetryStrategyTest { @Test public void testIMDSRetry() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); int retry = 0; Queue<Long> expectedEntries = new LinkedList<>(); expectedEntries.addAll(Arrays.asList(800L, 1600L, 3200L, 6400L, 12800L)); while (retry < imdsRetryStrategy.getMaxRetries()) { long timeout = (imdsRetryStrategy.calculateRetryDelay(retry).toMillis()); if (expectedEntries.contains(timeout)) { expectedEntries.remove(timeout); } else { Assertions.fail("Unexpected timeout: " + timeout); } retry++; } } @Test @Test public void testShouldRetryOnException() { ImdsRetryStrategy imdsRetryStrategy = new ImdsRetryStrategy(); Assertions.assertFalse(imdsRetryStrategy.shouldRetryException(new Exception("Test Error")), "Imds Retry Strategy should not retry on general exception."); Assertions.assertTrue(imdsRetryStrategy.shouldRetryException(new IOException("Test Error")), "Imds Retry Strategy should retry on IOException."); } }
just out of the curiosity, why we are providing other credentials if only AzurePipelinesCredentialBuilder is recommended?
public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); }
builder.addLast(new AzurePipelinesCredentialBuilder()
public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()); } else { builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } }
and it should be added as a first credential in the chain?
public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); }
builder.addLast(new AzurePipelinesCredentialBuilder()
public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()); } else { builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } }
This function was shared by the azure-sdk engg team. They have a plan to move this to a BaseTestClass so that each team neednt replicate it. Hence I havent checked what would make sense for us. Just reusing the exact function for now
public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); }
builder.addLast(new AzurePipelinesCredentialBuilder()
public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()); } else { builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } }
We can remove this if else, because this MockTokenCredential() is returned for playback mode inside getIdentityTestCredential method. It should be ``` builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } ```
protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()); } else { builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; }
builder.credential(new MockTokenCredential());
protected CommunicationIdentityClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); builder .endpoint(communicationEndpoint) .httpClient(httpClient); builder.credential(getIdentityTestCredential(interceptorManager)); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
class CommunicationIdentityClientTestBase extends TestProxyTestBase { private static final ClientLogger LOGGER = new ClientLogger(CommunicationIdentityClientTestBase.class); private static final String REDACTED = "REDACTED"; private static final String URI_IDENTITY_REPLACER_REGEX = "/identities/([^/?]+)"; protected static final String SYNC_TEST_SUFFIX = "Sync"; protected static final List<CommunicationTokenScope> SCOPES = Arrays.asList(CHAT, VOIP); protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https: protected HttpClient httpClient; @Override public void beforeTest() { getHttpClients().forEach(client -> this.httpClient = client); } protected HttpClient buildSyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertSync() .build(); } protected HttpClient buildAsyncAssertingClient(HttpClient httpClient) { HttpClient client = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient; return new AssertingHttpClientBuilder(client) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } protected CommunicationIdentityClientBuilder createClientBuilder(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); String communicationEndpoint = communicationConnectionString.getEndpoint(); String communicationAccessKey = communicationConnectionString.getAccessKey(); builder .endpoint(communicationEndpoint) .credential(new AzureKeyCredential(communicationAccessKey)) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } protected CommunicationIdentityClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); builder .connectionString(CONNECTION_STRING) .httpClient(httpClient); if (interceptorManager.isRecordMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()); } addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } private void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("$..id", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..token", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..appId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer("$..userId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); customSanitizers.add(new TestProxySanitizer(URI_IDENTITY_REPLACER_REGEX, "/identities/" + REDACTED, TestProxySanitizerType.URL)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { /** Skipping matching authentication headers since running in playback mode don't rely on environment variables */ interceptorManager.addMatchers(Collections.singletonList( new CustomMatcher().setExcludedHeaders(Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha256")))); } } protected CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } protected CommunicationIdentityAsyncClient setupAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityClientBuilder addLoggingPolicy(CommunicationIdentityClientBuilder builder, String testName) { return builder.addPolicy((context, next) -> logHeaders(testName, next)); } private Mono<HttpResponse> logHeaders(String testName, HttpPipelineNextPolicy next) { return next.process() .flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); LOGGER.log(LogLevel.VERBOSE, () -> "MS-CV header for " + testName + " request " + bufferedResponse.getRequest().getUrl() + ": " + bufferedResponse.getHeaderValue("MS-CV")); return Mono.just(bufferedResponse); }); } protected void verifyTokenNotEmpty(AccessToken issuedToken) { assertNotNull(issuedToken); assertNotNull(issuedToken.getToken()); assertFalse(issuedToken.getToken().isEmpty()); assertNotNull(issuedToken.getExpiresAt()); assertFalse(issuedToken.getExpiresAt().toString().isEmpty()); } protected void verifyUserNotEmpty(CommunicationUserIdentifier userIdentifier) { assertNotNull(userIdentifier); assertNotNull(userIdentifier.getId()); assertFalse(userIdentifier.getId().isEmpty()); } public static TokenCredential getIdentityTestCredential(InterceptorManager interceptorManager) { if (interceptorManager.isPlaybackMode()) { return new MockTokenCredential(); } Configuration config = Configuration.getGlobalConfiguration(); ChainedTokenCredentialBuilder builder = new ChainedTokenCredentialBuilder() .addLast(new EnvironmentCredentialBuilder().build()) .addLast(new AzureCliCredentialBuilder().build()) .addLast(new AzureDeveloperCliCredentialBuilder().build()); String serviceConnectionId = config.get("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); String clientId = config.get("AZURESUBSCRIPTION_CLIENT_ID"); String tenantId = config.get("AZURESUBSCRIPTION_TENANT_ID"); String systemAccessToken = config.get("SYSTEM_ACCESSTOKEN"); if (!CoreUtils.isNullOrEmpty(serviceConnectionId) && !CoreUtils.isNullOrEmpty(clientId) && !CoreUtils.isNullOrEmpty(tenantId) && !CoreUtils.isNullOrEmpty(systemAccessToken)) { builder.addLast(new AzurePipelinesCredentialBuilder() .systemAccessToken(systemAccessToken) .clientId(clientId) .tenantId(tenantId) .serviceConnectionId(serviceConnectionId) .build()); } builder.addLast(new AzurePowerShellCredentialBuilder().build()); return builder.build(); } }
not really, only if we have weird errors with null messages and want to have some indication in the log that exception has happened. I assume it's never the case and it can be simplified.
private String getMessageWithContext(String message, Throwable throwable) { if (message == null) { message = ""; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeStartObject().writeStringField("az.sdk.message", message); if (throwable != null) { String exceptionMessage = throwable.getMessage(); if (exceptionMessage != null) { jsonWriter.writeStringField("exception", exceptionMessage); } else { jsonWriter.writeNullField("exception"); } } if (hasGlobalContext) { jsonWriter.flush(); outputStream.write(','); outputStream.write(globalContextCached); } if (context != null) { for (ContextKeyValuePair contextKeyValuePair : context) { contextKeyValuePair.write(jsonWriter); } } jsonWriter.writeEndObject().flush(); return outputStream.toString(StandardCharsets.UTF_8); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
private String getMessageWithContext(String message, Throwable throwable) { if (message == null) { message = ""; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeStartObject().writeStringField("az.sdk.message", message); if (throwable != null) { jsonWriter.writeNullableField("exception", throwable.getMessage(), JsonWriter::writeString); } if (hasGlobalContext) { for (Map.Entry<String, Object> entry : globalContext.entrySet()) { jsonWriter.writeUntypedField(entry.getKey(), entry.getValue()); } } if (context != null) { for (ContextKeyValuePair contextKeyValuePair : context) { contextKeyValuePair.write(jsonWriter); } } jsonWriter.writeEndObject().flush(); return outputStream.toString(StandardCharsets.UTF_8); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
class LoggingEventBuilder { private static final LoggingEventBuilder NOOP = new LoggingEventBuilder(null, null, null, false); private static final byte[] EMPTY_BYTES = new byte[0]; private final Logger logger; private final LogLevel level; private List<ContextKeyValuePair> context; private final byte[] globalContextCached; private final boolean hasGlobalContext; private final boolean isEnabled; /** * Creates {@code LoggingEventBuilder} for provided level and {@link ClientLogger}. * If level is disabled, returns no-op instance. */ static LoggingEventBuilder create(Logger logger, LogLevel level, byte[] globalContextSerialized, boolean canLogAtLevel) { if (canLogAtLevel) { return new LoggingEventBuilder(logger, level, globalContextSerialized, true); } return NOOP; } private LoggingEventBuilder(Logger logger, LogLevel level, byte[] globalContextSerialized, boolean isEnabled) { this.logger = logger; this.level = level; this.isEnabled = isEnabled; this.globalContextCached = globalContextSerialized == null ? new byte[0] : globalContextSerialized; this.hasGlobalContext = this.globalContextCached.length > 0; } /** * Adds key with String value pair to the context of current log being created. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atInfo --> * <pre> * logger.atInfo& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atInfo --> * * @param key String key. * @param value String value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, String value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with Object value to the context of current log being created. * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to * serialize object. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * & * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value Object value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Object value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with boolean value to the context of current log being created. * * @param key String key. * @param value boolean value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, boolean value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with long value to the context of current log event being created. * * <p><strong>Code samples</strong></p> * * <p>Adding an integer value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value long value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, long value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with String value supplier to the context of current log event being created. * * @param key String key. * @param valueSupplier String value supplier function. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Supplier<String> valueSupplier) { if (this.isEnabled) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, valueSupplier)); } return this; } /** * Logs message annotated with context. * * @param message the message to log. */ public void log(String message) { if (this.isEnabled) { performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. */ public void log(Supplier<String> messageSupplier) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. * @param throwable {@link Throwable} for the message. */ public void log(Supplier<String> messageSupplier, Throwable throwable) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, throwable), logger.isDebugEnabled() ? throwable : null); } } /** * Logs a format-able message that uses {@code {}} as the placeholder at {@code warning} log level. * * @param format The format-able message to log. * @param args Arguments for the message. If an exception is being logged, the last argument should be the {@link * Throwable}. */ public void log(String format, Object... args) { if (this.isEnabled) { performLogging(level, format, args); } } /** * Logs the {@link Throwable} and returns it to be thrown. * * @param throwable Throwable to be logged and returned. * @return The passed {@link Throwable}. * @throws NullPointerException If {@code throwable} is {@code null}. */ public Throwable log(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, throwable), logger.isDebugEnabled() ? throwable : null); } return throwable; } /** * Logs the {@link RuntimeException} and returns it to be thrown. * This API covers the cases where a checked exception type needs to be thrown and logged. * * @param runtimeException RuntimeException to be logged and returned. * @return The passed {@link RuntimeException}. * @throws NullPointerException If {@code runtimeException} is {@code null}. */ public RuntimeException log(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, runtimeException), logger.isDebugEnabled() ? runtimeException : null); } return runtimeException; } /** * Creates the JSON representation for the logging event. * * @param message the message to log. * @param throwable {@link Throwable} for the message. * @return JSON representation for the logging event. * @throws UncheckedIOException If an I/O error occurs. */ private void addKeyValueInternal(String key, Object value) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, value)); } /* * Performs the logging. * * @param format format-able message. * * @param args Arguments for the message, if an exception is being logged last argument is the throwable. */ private void performLogging(LogLevel logLevel, String format, Object... args) { Throwable throwable = null; if (doesArgsHaveThrowable(args)) { Object throwableObj = args[args.length - 1]; if (throwableObj instanceof Throwable) { throwable = (Throwable) throwableObj; } /* * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } FormattingTuple tuple = MessageFormatter.arrayFormat(format, args); String message = getMessageWithContext(tuple.getMessage(), throwable); performLogging(logLevel, message, tuple.getThrowable()); } private void performLogging(LogLevel logLevel, String message, Throwable throwable) { switch (logLevel) { case VERBOSE: logger.debug(message, throwable); break; case INFORMATIONAL: logger.info(message, throwable); break; case WARNING: logger.warn(message, throwable); break; case ERROR: logger.error(message, throwable); break; default: break; } } /** * Serializes passed map to string containing valid JSON fragment: * e.g. "k1":"v1","k2":"v2", properly escaped and without trailing comma. * <p> * For complex object serialization, it calls {@code toString()} guarded with null check. * * @param context to serialize. * @return Serialized JSON fragment or an empty string. * @throws UncheckedIOException If an I/O error occurs. */ static byte[] writeJsonFragment(Map<String, Object> context) { if (CoreUtils.isNullOrEmpty(context)) { return EMPTY_BYTES; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeMap(context, JsonWriter::writeUntyped).flush(); return outputStream.toByteArray(1, outputStream.count() - 1); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static final class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. * * @throws IOException If an error occurs while writing the JSON. */ public void write(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField(key, (valueSupplier == null) ? value : valueSupplier.get()); } } }
class LoggingEventBuilder { private static final LoggingEventBuilder NOOP = new LoggingEventBuilder(null, null, null, false); private static final byte[] EMPTY_BYTES = new byte[0]; private final Logger logger; private final LogLevel level; private List<ContextKeyValuePair> context; private final Map<String, Object> globalContext; private final boolean hasGlobalContext; private final boolean isEnabled; /** * Creates {@code LoggingEventBuilder} for provided level and {@link ClientLogger}. * If level is disabled, returns no-op instance. */ static LoggingEventBuilder create(Logger logger, LogLevel level, Map<String, Object> globalContext, boolean canLogAtLevel) { if (canLogAtLevel) { return new LoggingEventBuilder(logger, level, globalContext, true); } return NOOP; } private LoggingEventBuilder(Logger logger, LogLevel level, Map<String, Object> globalContext, boolean isEnabled) { this.logger = logger; this.level = level; this.isEnabled = isEnabled; this.globalContext = globalContext; this.hasGlobalContext = !CoreUtils.isNullOrEmpty(globalContext); } /** * Adds key with String value pair to the context of current log being created. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atInfo --> * <pre> * logger.atInfo& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atInfo --> * * @param key String key. * @param value String value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, String value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with Object value to the context of current log being created. * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to * serialize object. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * & * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value Object value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Object value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with boolean value to the context of current log being created. * * @param key String key. * @param value boolean value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, boolean value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with long value to the context of current log event being created. * * <p><strong>Code samples</strong></p> * * <p>Adding an integer value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value long value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, long value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with String value supplier to the context of current log event being created. * * @param key String key. * @param valueSupplier String value supplier function. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Supplier<String> valueSupplier) { if (this.isEnabled) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, valueSupplier)); } return this; } /** * Logs message annotated with context. * * @param message the message to log. */ public void log(String message) { if (this.isEnabled) { performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. */ public void log(Supplier<String> messageSupplier) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. * @param throwable {@link Throwable} for the message. */ public void log(Supplier<String> messageSupplier, Throwable throwable) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, throwable), logger.isDebugEnabled() ? throwable : null); } } /** * Logs a format-able message that uses {@code {}} as the placeholder at {@code warning} log level. * * @param format The format-able message to log. * @param args Arguments for the message. If an exception is being logged, the last argument should be the {@link * Throwable}. */ public void log(String format, Object... args) { if (this.isEnabled) { performLogging(level, format, args); } } /** * Logs the {@link Throwable} and returns it to be thrown. * * @param throwable Throwable to be logged and returned. * @return The passed {@link Throwable}. * @throws NullPointerException If {@code throwable} is {@code null}. */ public Throwable log(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, throwable), logger.isDebugEnabled() ? throwable : null); } return throwable; } /** * Logs the {@link RuntimeException} and returns it to be thrown. * This API covers the cases where a checked exception type needs to be thrown and logged. * * @param runtimeException RuntimeException to be logged and returned. * @return The passed {@link RuntimeException}. * @throws NullPointerException If {@code runtimeException} is {@code null}. */ public RuntimeException log(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, runtimeException), logger.isDebugEnabled() ? runtimeException : null); } return runtimeException; } /** * Creates the JSON representation for the logging event. * * @param message the message to log. * @param throwable {@link Throwable} for the message. * @return JSON representation for the logging event. * @throws UncheckedIOException If an I/O error occurs. */ private void addKeyValueInternal(String key, Object value) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, value)); } /* * Performs the logging. * * @param format format-able message. * * @param args Arguments for the message, if an exception is being logged last argument is the throwable. */ private void performLogging(LogLevel logLevel, String format, Object... args) { Throwable throwable = null; if (doesArgsHaveThrowable(args)) { Object throwableObj = args[args.length - 1]; if (throwableObj instanceof Throwable) { throwable = (Throwable) throwableObj; } /* * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } FormattingTuple tuple = MessageFormatter.arrayFormat(format, args); String message = getMessageWithContext(tuple.getMessage(), throwable); performLogging(logLevel, message, tuple.getThrowable()); } private void performLogging(LogLevel logLevel, String message, Throwable throwable) { switch (logLevel) { case VERBOSE: logger.debug(message, throwable); break; case INFORMATIONAL: logger.info(message, throwable); break; case WARNING: logger.warn(message, throwable); break; case ERROR: logger.error(message, throwable); break; default: break; } } private static final class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. * * @throws IOException If an error occurs while writing the JSON. */ public void write(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField(key, (valueSupplier == null) ? value : valueSupplier.get()); } } }
is this necessary?
private String getMessageWithContext(String message, Throwable throwable) { if (message == null) { message = ""; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeStartObject().writeStringField("az.sdk.message", message); if (throwable != null) { String exceptionMessage = throwable.getMessage(); if (exceptionMessage != null) { jsonWriter.writeStringField("exception", exceptionMessage); } else { jsonWriter.writeNullField("exception"); } } if (hasGlobalContext) { jsonWriter.flush(); outputStream.write(','); outputStream.write(globalContextCached); } if (context != null) { for (ContextKeyValuePair contextKeyValuePair : context) { contextKeyValuePair.write(jsonWriter); } } jsonWriter.writeEndObject().flush(); return outputStream.toString(StandardCharsets.UTF_8); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
jsonWriter.flush();
private String getMessageWithContext(String message, Throwable throwable) { if (message == null) { message = ""; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeStartObject().writeStringField("az.sdk.message", message); if (throwable != null) { jsonWriter.writeNullableField("exception", throwable.getMessage(), JsonWriter::writeString); } if (hasGlobalContext) { for (Map.Entry<String, Object> entry : globalContext.entrySet()) { jsonWriter.writeUntypedField(entry.getKey(), entry.getValue()); } } if (context != null) { for (ContextKeyValuePair contextKeyValuePair : context) { contextKeyValuePair.write(jsonWriter); } } jsonWriter.writeEndObject().flush(); return outputStream.toString(StandardCharsets.UTF_8); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
class LoggingEventBuilder { private static final LoggingEventBuilder NOOP = new LoggingEventBuilder(null, null, null, false); private static final byte[] EMPTY_BYTES = new byte[0]; private final Logger logger; private final LogLevel level; private List<ContextKeyValuePair> context; private final byte[] globalContextCached; private final boolean hasGlobalContext; private final boolean isEnabled; /** * Creates {@code LoggingEventBuilder} for provided level and {@link ClientLogger}. * If level is disabled, returns no-op instance. */ static LoggingEventBuilder create(Logger logger, LogLevel level, byte[] globalContextSerialized, boolean canLogAtLevel) { if (canLogAtLevel) { return new LoggingEventBuilder(logger, level, globalContextSerialized, true); } return NOOP; } private LoggingEventBuilder(Logger logger, LogLevel level, byte[] globalContextSerialized, boolean isEnabled) { this.logger = logger; this.level = level; this.isEnabled = isEnabled; this.globalContextCached = globalContextSerialized == null ? new byte[0] : globalContextSerialized; this.hasGlobalContext = this.globalContextCached.length > 0; } /** * Adds key with String value pair to the context of current log being created. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atInfo --> * <pre> * logger.atInfo& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atInfo --> * * @param key String key. * @param value String value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, String value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with Object value to the context of current log being created. * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to * serialize object. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * & * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value Object value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Object value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with boolean value to the context of current log being created. * * @param key String key. * @param value boolean value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, boolean value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with long value to the context of current log event being created. * * <p><strong>Code samples</strong></p> * * <p>Adding an integer value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value long value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, long value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with String value supplier to the context of current log event being created. * * @param key String key. * @param valueSupplier String value supplier function. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Supplier<String> valueSupplier) { if (this.isEnabled) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, valueSupplier)); } return this; } /** * Logs message annotated with context. * * @param message the message to log. */ public void log(String message) { if (this.isEnabled) { performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. */ public void log(Supplier<String> messageSupplier) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. * @param throwable {@link Throwable} for the message. */ public void log(Supplier<String> messageSupplier, Throwable throwable) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, throwable), logger.isDebugEnabled() ? throwable : null); } } /** * Logs a format-able message that uses {@code {}} as the placeholder at {@code warning} log level. * * @param format The format-able message to log. * @param args Arguments for the message. If an exception is being logged, the last argument should be the {@link * Throwable}. */ public void log(String format, Object... args) { if (this.isEnabled) { performLogging(level, format, args); } } /** * Logs the {@link Throwable} and returns it to be thrown. * * @param throwable Throwable to be logged and returned. * @return The passed {@link Throwable}. * @throws NullPointerException If {@code throwable} is {@code null}. */ public Throwable log(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, throwable), logger.isDebugEnabled() ? throwable : null); } return throwable; } /** * Logs the {@link RuntimeException} and returns it to be thrown. * This API covers the cases where a checked exception type needs to be thrown and logged. * * @param runtimeException RuntimeException to be logged and returned. * @return The passed {@link RuntimeException}. * @throws NullPointerException If {@code runtimeException} is {@code null}. */ public RuntimeException log(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, runtimeException), logger.isDebugEnabled() ? runtimeException : null); } return runtimeException; } /** * Creates the JSON representation for the logging event. * * @param message the message to log. * @param throwable {@link Throwable} for the message. * @return JSON representation for the logging event. * @throws UncheckedIOException If an I/O error occurs. */ private void addKeyValueInternal(String key, Object value) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, value)); } /* * Performs the logging. * * @param format format-able message. * * @param args Arguments for the message, if an exception is being logged last argument is the throwable. */ private void performLogging(LogLevel logLevel, String format, Object... args) { Throwable throwable = null; if (doesArgsHaveThrowable(args)) { Object throwableObj = args[args.length - 1]; if (throwableObj instanceof Throwable) { throwable = (Throwable) throwableObj; } /* * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } FormattingTuple tuple = MessageFormatter.arrayFormat(format, args); String message = getMessageWithContext(tuple.getMessage(), throwable); performLogging(logLevel, message, tuple.getThrowable()); } private void performLogging(LogLevel logLevel, String message, Throwable throwable) { switch (logLevel) { case VERBOSE: logger.debug(message, throwable); break; case INFORMATIONAL: logger.info(message, throwable); break; case WARNING: logger.warn(message, throwable); break; case ERROR: logger.error(message, throwable); break; default: break; } } /** * Serializes passed map to string containing valid JSON fragment: * e.g. "k1":"v1","k2":"v2", properly escaped and without trailing comma. * <p> * For complex object serialization, it calls {@code toString()} guarded with null check. * * @param context to serialize. * @return Serialized JSON fragment or an empty string. * @throws UncheckedIOException If an I/O error occurs. */ static byte[] writeJsonFragment(Map<String, Object> context) { if (CoreUtils.isNullOrEmpty(context)) { return EMPTY_BYTES; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeMap(context, JsonWriter::writeUntyped).flush(); return outputStream.toByteArray(1, outputStream.count() - 1); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static final class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. * * @throws IOException If an error occurs while writing the JSON. */ public void write(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField(key, (valueSupplier == null) ? value : valueSupplier.get()); } } }
class LoggingEventBuilder { private static final LoggingEventBuilder NOOP = new LoggingEventBuilder(null, null, null, false); private static final byte[] EMPTY_BYTES = new byte[0]; private final Logger logger; private final LogLevel level; private List<ContextKeyValuePair> context; private final Map<String, Object> globalContext; private final boolean hasGlobalContext; private final boolean isEnabled; /** * Creates {@code LoggingEventBuilder} for provided level and {@link ClientLogger}. * If level is disabled, returns no-op instance. */ static LoggingEventBuilder create(Logger logger, LogLevel level, Map<String, Object> globalContext, boolean canLogAtLevel) { if (canLogAtLevel) { return new LoggingEventBuilder(logger, level, globalContext, true); } return NOOP; } private LoggingEventBuilder(Logger logger, LogLevel level, Map<String, Object> globalContext, boolean isEnabled) { this.logger = logger; this.level = level; this.isEnabled = isEnabled; this.globalContext = globalContext; this.hasGlobalContext = !CoreUtils.isNullOrEmpty(globalContext); } /** * Adds key with String value pair to the context of current log being created. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atInfo --> * <pre> * logger.atInfo& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atInfo --> * * @param key String key. * @param value String value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, String value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with Object value to the context of current log being created. * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to * serialize object. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * & * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value Object value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Object value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with boolean value to the context of current log being created. * * @param key String key. * @param value boolean value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, boolean value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with long value to the context of current log event being created. * * <p><strong>Code samples</strong></p> * * <p>Adding an integer value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value long value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, long value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with String value supplier to the context of current log event being created. * * @param key String key. * @param valueSupplier String value supplier function. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Supplier<String> valueSupplier) { if (this.isEnabled) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, valueSupplier)); } return this; } /** * Logs message annotated with context. * * @param message the message to log. */ public void log(String message) { if (this.isEnabled) { performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. */ public void log(Supplier<String> messageSupplier) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. * @param throwable {@link Throwable} for the message. */ public void log(Supplier<String> messageSupplier, Throwable throwable) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, throwable), logger.isDebugEnabled() ? throwable : null); } } /** * Logs a format-able message that uses {@code {}} as the placeholder at {@code warning} log level. * * @param format The format-able message to log. * @param args Arguments for the message. If an exception is being logged, the last argument should be the {@link * Throwable}. */ public void log(String format, Object... args) { if (this.isEnabled) { performLogging(level, format, args); } } /** * Logs the {@link Throwable} and returns it to be thrown. * * @param throwable Throwable to be logged and returned. * @return The passed {@link Throwable}. * @throws NullPointerException If {@code throwable} is {@code null}. */ public Throwable log(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, throwable), logger.isDebugEnabled() ? throwable : null); } return throwable; } /** * Logs the {@link RuntimeException} and returns it to be thrown. * This API covers the cases where a checked exception type needs to be thrown and logged. * * @param runtimeException RuntimeException to be logged and returned. * @return The passed {@link RuntimeException}. * @throws NullPointerException If {@code runtimeException} is {@code null}. */ public RuntimeException log(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, runtimeException), logger.isDebugEnabled() ? runtimeException : null); } return runtimeException; } /** * Creates the JSON representation for the logging event. * * @param message the message to log. * @param throwable {@link Throwable} for the message. * @return JSON representation for the logging event. * @throws UncheckedIOException If an I/O error occurs. */ private void addKeyValueInternal(String key, Object value) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, value)); } /* * Performs the logging. * * @param format format-able message. * * @param args Arguments for the message, if an exception is being logged last argument is the throwable. */ private void performLogging(LogLevel logLevel, String format, Object... args) { Throwable throwable = null; if (doesArgsHaveThrowable(args)) { Object throwableObj = args[args.length - 1]; if (throwableObj instanceof Throwable) { throwable = (Throwable) throwableObj; } /* * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } FormattingTuple tuple = MessageFormatter.arrayFormat(format, args); String message = getMessageWithContext(tuple.getMessage(), throwable); performLogging(logLevel, message, tuple.getThrowable()); } private void performLogging(LogLevel logLevel, String message, Throwable throwable) { switch (logLevel) { case VERBOSE: logger.debug(message, throwable); break; case INFORMATIONAL: logger.info(message, throwable); break; case WARNING: logger.warn(message, throwable); break; case ERROR: logger.error(message, throwable); break; default: break; } } private static final class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. * * @throws IOException If an error occurs while writing the JSON. */ public void write(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField(key, (valueSupplier == null) ? value : valueSupplier.get()); } } }
It can be if the JsonWriter implementation has a buffer that allows it to not need to flush contents to the backing store each write operation. But this could be removed by using a global context Map instead of a pre-serialized string.
private String getMessageWithContext(String message, Throwable throwable) { if (message == null) { message = ""; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeStartObject().writeStringField("az.sdk.message", message); if (throwable != null) { String exceptionMessage = throwable.getMessage(); if (exceptionMessage != null) { jsonWriter.writeStringField("exception", exceptionMessage); } else { jsonWriter.writeNullField("exception"); } } if (hasGlobalContext) { jsonWriter.flush(); outputStream.write(','); outputStream.write(globalContextCached); } if (context != null) { for (ContextKeyValuePair contextKeyValuePair : context) { contextKeyValuePair.write(jsonWriter); } } jsonWriter.writeEndObject().flush(); return outputStream.toString(StandardCharsets.UTF_8); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
jsonWriter.flush();
private String getMessageWithContext(String message, Throwable throwable) { if (message == null) { message = ""; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeStartObject().writeStringField("az.sdk.message", message); if (throwable != null) { jsonWriter.writeNullableField("exception", throwable.getMessage(), JsonWriter::writeString); } if (hasGlobalContext) { for (Map.Entry<String, Object> entry : globalContext.entrySet()) { jsonWriter.writeUntypedField(entry.getKey(), entry.getValue()); } } if (context != null) { for (ContextKeyValuePair contextKeyValuePair : context) { contextKeyValuePair.write(jsonWriter); } } jsonWriter.writeEndObject().flush(); return outputStream.toString(StandardCharsets.UTF_8); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
class LoggingEventBuilder { private static final LoggingEventBuilder NOOP = new LoggingEventBuilder(null, null, null, false); private static final byte[] EMPTY_BYTES = new byte[0]; private final Logger logger; private final LogLevel level; private List<ContextKeyValuePair> context; private final byte[] globalContextCached; private final boolean hasGlobalContext; private final boolean isEnabled; /** * Creates {@code LoggingEventBuilder} for provided level and {@link ClientLogger}. * If level is disabled, returns no-op instance. */ static LoggingEventBuilder create(Logger logger, LogLevel level, byte[] globalContextSerialized, boolean canLogAtLevel) { if (canLogAtLevel) { return new LoggingEventBuilder(logger, level, globalContextSerialized, true); } return NOOP; } private LoggingEventBuilder(Logger logger, LogLevel level, byte[] globalContextSerialized, boolean isEnabled) { this.logger = logger; this.level = level; this.isEnabled = isEnabled; this.globalContextCached = globalContextSerialized == null ? new byte[0] : globalContextSerialized; this.hasGlobalContext = this.globalContextCached.length > 0; } /** * Adds key with String value pair to the context of current log being created. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atInfo --> * <pre> * logger.atInfo& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atInfo --> * * @param key String key. * @param value String value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, String value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with Object value to the context of current log being created. * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to * serialize object. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * & * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value Object value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Object value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with boolean value to the context of current log being created. * * @param key String key. * @param value boolean value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, boolean value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with long value to the context of current log event being created. * * <p><strong>Code samples</strong></p> * * <p>Adding an integer value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value long value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, long value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with String value supplier to the context of current log event being created. * * @param key String key. * @param valueSupplier String value supplier function. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Supplier<String> valueSupplier) { if (this.isEnabled) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, valueSupplier)); } return this; } /** * Logs message annotated with context. * * @param message the message to log. */ public void log(String message) { if (this.isEnabled) { performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. */ public void log(Supplier<String> messageSupplier) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. * @param throwable {@link Throwable} for the message. */ public void log(Supplier<String> messageSupplier, Throwable throwable) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, throwable), logger.isDebugEnabled() ? throwable : null); } } /** * Logs a format-able message that uses {@code {}} as the placeholder at {@code warning} log level. * * @param format The format-able message to log. * @param args Arguments for the message. If an exception is being logged, the last argument should be the {@link * Throwable}. */ public void log(String format, Object... args) { if (this.isEnabled) { performLogging(level, format, args); } } /** * Logs the {@link Throwable} and returns it to be thrown. * * @param throwable Throwable to be logged and returned. * @return The passed {@link Throwable}. * @throws NullPointerException If {@code throwable} is {@code null}. */ public Throwable log(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, throwable), logger.isDebugEnabled() ? throwable : null); } return throwable; } /** * Logs the {@link RuntimeException} and returns it to be thrown. * This API covers the cases where a checked exception type needs to be thrown and logged. * * @param runtimeException RuntimeException to be logged and returned. * @return The passed {@link RuntimeException}. * @throws NullPointerException If {@code runtimeException} is {@code null}. */ public RuntimeException log(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, runtimeException), logger.isDebugEnabled() ? runtimeException : null); } return runtimeException; } /** * Creates the JSON representation for the logging event. * * @param message the message to log. * @param throwable {@link Throwable} for the message. * @return JSON representation for the logging event. * @throws UncheckedIOException If an I/O error occurs. */ private void addKeyValueInternal(String key, Object value) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, value)); } /* * Performs the logging. * * @param format format-able message. * * @param args Arguments for the message, if an exception is being logged last argument is the throwable. */ private void performLogging(LogLevel logLevel, String format, Object... args) { Throwable throwable = null; if (doesArgsHaveThrowable(args)) { Object throwableObj = args[args.length - 1]; if (throwableObj instanceof Throwable) { throwable = (Throwable) throwableObj; } /* * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } FormattingTuple tuple = MessageFormatter.arrayFormat(format, args); String message = getMessageWithContext(tuple.getMessage(), throwable); performLogging(logLevel, message, tuple.getThrowable()); } private void performLogging(LogLevel logLevel, String message, Throwable throwable) { switch (logLevel) { case VERBOSE: logger.debug(message, throwable); break; case INFORMATIONAL: logger.info(message, throwable); break; case WARNING: logger.warn(message, throwable); break; case ERROR: logger.error(message, throwable); break; default: break; } } /** * Serializes passed map to string containing valid JSON fragment: * e.g. "k1":"v1","k2":"v2", properly escaped and without trailing comma. * <p> * For complex object serialization, it calls {@code toString()} guarded with null check. * * @param context to serialize. * @return Serialized JSON fragment or an empty string. * @throws UncheckedIOException If an I/O error occurs. */ static byte[] writeJsonFragment(Map<String, Object> context) { if (CoreUtils.isNullOrEmpty(context)) { return EMPTY_BYTES; } try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { jsonWriter.writeMap(context, JsonWriter::writeUntyped).flush(); return outputStream.toByteArray(1, outputStream.count() - 1); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static final class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. * * @throws IOException If an error occurs while writing the JSON. */ public void write(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField(key, (valueSupplier == null) ? value : valueSupplier.get()); } } }
class LoggingEventBuilder { private static final LoggingEventBuilder NOOP = new LoggingEventBuilder(null, null, null, false); private static final byte[] EMPTY_BYTES = new byte[0]; private final Logger logger; private final LogLevel level; private List<ContextKeyValuePair> context; private final Map<String, Object> globalContext; private final boolean hasGlobalContext; private final boolean isEnabled; /** * Creates {@code LoggingEventBuilder} for provided level and {@link ClientLogger}. * If level is disabled, returns no-op instance. */ static LoggingEventBuilder create(Logger logger, LogLevel level, Map<String, Object> globalContext, boolean canLogAtLevel) { if (canLogAtLevel) { return new LoggingEventBuilder(logger, level, globalContext, true); } return NOOP; } private LoggingEventBuilder(Logger logger, LogLevel level, Map<String, Object> globalContext, boolean isEnabled) { this.logger = logger; this.level = level; this.isEnabled = isEnabled; this.globalContext = globalContext; this.hasGlobalContext = !CoreUtils.isNullOrEmpty(globalContext); } /** * Adds key with String value pair to the context of current log being created. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atInfo --> * <pre> * logger.atInfo& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atInfo --> * * @param key String key. * @param value String value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, String value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with Object value to the context of current log being created. * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to * serialize object. * * <p><strong>Code samples</strong></p> * * <p>Adding string value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * & * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value Object value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Object value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with boolean value to the context of current log being created. * * @param key String key. * @param value boolean value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, boolean value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with long value to the context of current log event being created. * * <p><strong>Code samples</strong></p> * * <p>Adding an integer value to logging event context.</p> * * <!-- src_embed com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * <pre> * logger.atVerbose& * .addKeyValue& * .log& * </pre> * <!-- end com.azure.core.util.logging.clientlogger.atverbose.addKeyValue * * @param key String key. * @param value long value. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, long value) { if (this.isEnabled) { addKeyValueInternal(key, value); } return this; } /** * Adds key with String value supplier to the context of current log event being created. * * @param key String key. * @param valueSupplier String value supplier function. * @return The updated {@code LoggingEventBuilder} object. */ public LoggingEventBuilder addKeyValue(String key, Supplier<String> valueSupplier) { if (this.isEnabled) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, valueSupplier)); } return this; } /** * Logs message annotated with context. * * @param message the message to log. */ public void log(String message) { if (this.isEnabled) { performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. */ public void log(Supplier<String> messageSupplier) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, null), (Throwable) null); } } /** * Logs message annotated with context. * * @param messageSupplier string message supplier. * @param throwable {@link Throwable} for the message. */ public void log(Supplier<String> messageSupplier, Throwable throwable) { if (this.isEnabled) { String message = messageSupplier != null ? messageSupplier.get() : null; performLogging(level, getMessageWithContext(message, throwable), logger.isDebugEnabled() ? throwable : null); } } /** * Logs a format-able message that uses {@code {}} as the placeholder at {@code warning} log level. * * @param format The format-able message to log. * @param args Arguments for the message. If an exception is being logged, the last argument should be the {@link * Throwable}. */ public void log(String format, Object... args) { if (this.isEnabled) { performLogging(level, format, args); } } /** * Logs the {@link Throwable} and returns it to be thrown. * * @param throwable Throwable to be logged and returned. * @return The passed {@link Throwable}. * @throws NullPointerException If {@code throwable} is {@code null}. */ public Throwable log(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, throwable), logger.isDebugEnabled() ? throwable : null); } return throwable; } /** * Logs the {@link RuntimeException} and returns it to be thrown. * This API covers the cases where a checked exception type needs to be thrown and logged. * * @param runtimeException RuntimeException to be logged and returned. * @return The passed {@link RuntimeException}. * @throws NullPointerException If {@code runtimeException} is {@code null}. */ public RuntimeException log(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); if (this.isEnabled) { performLogging(level, getMessageWithContext(null, runtimeException), logger.isDebugEnabled() ? runtimeException : null); } return runtimeException; } /** * Creates the JSON representation for the logging event. * * @param message the message to log. * @param throwable {@link Throwable} for the message. * @return JSON representation for the logging event. * @throws UncheckedIOException If an I/O error occurs. */ private void addKeyValueInternal(String key, Object value) { if (this.context == null) { this.context = new ArrayList<>(); } this.context.add(new ContextKeyValuePair(key, value)); } /* * Performs the logging. * * @param format format-able message. * * @param args Arguments for the message, if an exception is being logged last argument is the throwable. */ private void performLogging(LogLevel logLevel, String format, Object... args) { Throwable throwable = null; if (doesArgsHaveThrowable(args)) { Object throwableObj = args[args.length - 1]; if (throwableObj instanceof Throwable) { throwable = (Throwable) throwableObj; } /* * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } FormattingTuple tuple = MessageFormatter.arrayFormat(format, args); String message = getMessageWithContext(tuple.getMessage(), throwable); performLogging(logLevel, message, tuple.getThrowable()); } private void performLogging(LogLevel logLevel, String message, Throwable throwable) { switch (logLevel) { case VERBOSE: logger.debug(message, throwable); break; case INFORMATIONAL: logger.info(message, throwable); break; case WARNING: logger.warn(message, throwable); break; case ERROR: logger.error(message, throwable); break; default: break; } } private static final class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. * * @throws IOException If an error occurs while writing the JSON. */ public void write(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField(key, (valueSupplier == null) ? value : valueSupplier.get()); } } }
Is this time out for PLAYBACK only, or time out for both? If PLAYBACK only, use `@DoNotRecord(skipInPlayback = true)` (`@LiveOnly` won't run in record mode)
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST_CENTRAL; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @LiveOnly public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @LiveOnly @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST2; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @DoNotRecord(skipInPlayback = true) @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
Fixed in the new version.
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST_CENTRAL; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @LiveOnly public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @LiveOnly @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST2; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @DoNotRecord(skipInPlayback = true) @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
Answer? Is this time out for PLAYBACK only, or time out for both?
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST_CENTRAL; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @LiveOnly public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @LiveOnly @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST2; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @DoNotRecord(skipInPlayback = true) @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
Yes, this is time out for PLAYBACK only.
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
public void canCreateVirtualMachineWithLMSIAndEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); ResourceGroup resourceGroup = resourceManager.resourceGroups().define(rgName).withRegion(region).create(); Network network = networkManager .networks() .define(networkName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessTo(network.id(), BuiltInRole.CONTRIBUTOR) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment .principalId() .equalsIgnoreCase(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for local identity" + virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( network.id(), BuiltInRole.CONTRIBUTOR, virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for system assigned identity"); ResourceGroup resourceGroup1 = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup1.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(identity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + identity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup1.id(), BuiltInRole.CONTRIBUTOR, identity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for system assigned identity"); }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST_CENTRAL; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @LiveOnly public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @LiveOnly @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_D2S_V3) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest { private String rgName = ""; private Region region = Region.US_WEST2; private final String vmName = "javavm"; @Override protected void cleanUpResources() { this.resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test @DoNotRecord(skipInPlayback = true) public void canCreateUpdateVirtualMachineWithEMSI() { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); String networkName = generateRandomResourceName("nw", 10); Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups().define(rgName).withRegion(region); final Network network = networkManager.networks().define(networkName).withRegion(region).withNewResourceGroup(creatableRG).create(); final Identity createdIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessTo(network, BuiltInRole.READER) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(2, emsiIds.size()); Identity implicitlyCreatedIdentity = null; for (String emsiId : emsiIds) { Identity identity = msiManager.identities().getById(emsiId); Assertions.assertNotNull(identity); Assertions .assertTrue( identity.name().equalsIgnoreCase(identityName1) || identity.name().equalsIgnoreCase(identityName2)); Assertions.assertNotNull(identity.principalId()); if (identity.name().equalsIgnoreCase(identityName2)) { implicitlyCreatedIdentity = identity; } } Assertions.assertNotNull(implicitlyCreatedIdentity); PagedIterable<RoleAssignment> roleAssignmentsForNetwork = this.msiManager.authorizationManager().roleAssignments().listByScope(network.id()); boolean found = false; for (RoleAssignment roleAssignment : roleAssignmentsForNetwork) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(createdIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the virtual network for identity" + createdIdentity.name()); RoleAssignment assignment = lookupRoleAssignmentUsingScopeAndRoleAsync(network.id(), BuiltInRole.READER, createdIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the virtual network for identity"); ResourceGroup resourceGroup = resourceManager.resourceGroups().getByName(virtualMachine.resourceGroupName()); Assertions.assertNotNull(resourceGroup); PagedIterable<RoleAssignment> roleAssignmentsForResourceGroup = this.msiManager.authorizationManager().roleAssignments().listByScope(resourceGroup.id()); found = false; for (RoleAssignment roleAssignment : roleAssignmentsForResourceGroup) { if (roleAssignment.principalId() != null && roleAssignment.principalId().equalsIgnoreCase(implicitlyCreatedIdentity.principalId())) { found = true; break; } } Assertions .assertTrue( found, "Expected role assignment not found for the resource group for identity" + implicitlyCreatedIdentity.name()); assignment = lookupRoleAssignmentUsingScopeAndRoleAsync( resourceGroup.id(), BuiltInRole.CONTRIBUTOR, implicitlyCreatedIdentity.principalId()) .block(); Assertions .assertNotNull( assignment, "Expected role assignment with ROLE not found for the resource group for identity"); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Iterator<String> itr = emsiIds.iterator(); virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(itr.next()) .withoutUserAssignedManagedServiceIdentity(itr.next()) .apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } virtualMachine.refresh(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } itr = emsiIds.iterator(); Identity identity1 = msiManager.identities().getById(itr.next()); Identity identity2 = msiManager.identities().getById(itr.next()); virtualMachine .update() .withSystemAssignedManagedServiceIdentity() .withExistingUserAssignedManagedServiceIdentity(identity1) .withExistingUserAssignedManagedServiceIdentity(identity2) .apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.refresh(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(2, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); itr = emsiIds.iterator(); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertNotNull(virtualMachine.userAssignedManagedServiceIdentityIds()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(itr.next()).apply(); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED)); } @Test @DoNotRecord(skipInPlayback = true) @Test public void canUpdateVirtualMachineWithEMSIAndLMSI() throws Exception { rgName = generateRandomResourceName("java-emsi-c-rg", 15); String identityName1 = generateRandomResourceName("msi-id-1", 15); String identityName2 = generateRandomResourceName("msi-id-2", 15); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withSsh(sshPublicKey()) .withSize(VirtualMachineSizeTypes.STANDARD_A0) .create(); Creatable<Identity> creatableIdentity = msiManager .identities() .define(identityName1) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); virtualMachine = virtualMachine.update().withNewUserAssignedManagedServiceIdentity(creatableIdentity).apply(); Set<String> emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName1)); virtualMachine.update() .withNewDataDisk(10) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); Identity createdIdentity = msiManager .identities() .define(identityName2) .withRegion(region) .withExistingResourceGroup(virtualMachine.resourceGroupName()) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); virtualMachine = virtualMachine .update() .withoutUserAssignedManagedServiceIdentity(identity.id()) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .apply(); emsiIds = virtualMachine.userAssignedManagedServiceIdentityIds(); Assertions.assertNotNull(emsiIds); Assertions.assertEquals(1, emsiIds.size()); identity = msiManager.identities().getById(emsiIds.iterator().next()); Assertions.assertNotNull(identity); Assertions.assertTrue(identity.name().equalsIgnoreCase(identityName2)); virtualMachine.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertNotNull(virtualMachine); Assertions.assertNotNull(virtualMachine.innerModel()); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions .assertTrue( virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED)); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNotNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(virtualMachine.isManagedServiceIdentityEnabled()); Assertions.assertNotNull(virtualMachine.managedServiceIdentityType()); Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.USER_ASSIGNED)); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(1, virtualMachine.userAssignedManagedServiceIdentityIds().size()); virtualMachine.update().withoutUserAssignedManagedServiceIdentity(identity.id()).apply(); Assertions.assertFalse(virtualMachine.isManagedServiceIdentityEnabled()); if (virtualMachine.managedServiceIdentityType() != null) { Assertions.assertTrue(virtualMachine.managedServiceIdentityType().equals(ResourceIdentityType.NONE)); } Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityPrincipalId()); Assertions.assertNull(virtualMachine.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertEquals(0, virtualMachine.userAssignedManagedServiceIdentityIds().size()); } private Mono<RoleAssignment> lookupRoleAssignmentUsingScopeAndRoleAsync( final String scope, BuiltInRole role, final String principalId) { return this .msiManager .authorizationManager() .roleDefinitions() .getByScopeAndRoleNameAsync(scope, role.toString()) .flatMap( roleDefinition -> msiManager .authorizationManager() .roleAssignments() .listByScopeAsync(scope) .filter( roleAssignment -> roleAssignment.roleDefinitionId().equalsIgnoreCase(roleDefinition.id()) && roleAssignment.principalId().equalsIgnoreCase(principalId)) .singleOrEmpty()) .switchIfEmpty(Mono.defer(() -> Mono.empty())); } }
What's the difference here?
public Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultClient", "getCertificateChain", alias); LOGGER.log(INFO, "Getting certificate chain for alias: {0}", alias); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "secrets/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response == null) { throw new NullPointerException(); } SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(response, SecretBundle.class); Certificate[] certificates = new Certificate[0]; try { certificates = loadCertificatesFromSecretBundleValue(secretBundle.getValue()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | PKCSException e) { LOGGER.log(WARNING, "Unable to decode certificate chain", e); } LOGGER.exiting("KeyVaultClient", "getCertificate", alias); return certificates; }
}
public Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultClient", "getCertificateChain", alias); LOGGER.log(INFO, "Getting certificate chain for alias: {0}", alias); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "secrets/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response == null) { throw new NullPointerException(); } SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(response, SecretBundle.class); Certificate[] certificates = new Certificate[0]; try { certificates = loadCertificatesFromSecretBundleValue(secretBundle.getValue()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | PKCSException e) { LOGGER.log(WARNING, "Unable to decode certificate chain", e); } LOGGER.exiting("KeyVaultClient", "getCertificate", alias); return certificates; }
class KeyVaultClient { private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the Key Vault cloud URI. */ private final String keyVaultBaseUri; /** * Stores the Azure Key Vault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private final String tenantId; /** * Stores the client ID. */ private final String clientId; /** * Stores the client secret. */ private final String clientSecret; /** * Stores the managed identity (either the user-assigned managed identity object ID or null if system-assigned). */ private String managedIdentity; /** * Stores the token. */ private AccessToken accessToken; /** * Stores a flag indicating if challenge resource verification shall be disabled. */ private final boolean disableChallengeResourceVerification; /** * Constructor for authentication with user-assigned managed identity. * * @param keyVaultUri The Azure Key Vault URI. * @param managedIdentity The user-assigned managed identity object ID. */ KeyVaultClient(String keyVaultUri, String managedIdentity) { this(keyVaultUri, null, null, null, managedIdentity, false); } /** * Constructor for authentication with service principal. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret) { this(keyVaultUri, tenantId, clientId, clientSecret, null, false); } /** * Constructor. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. * @param managedIdentity The user-assigned managed identity object ID. * @param disableChallengeResourceVerification Indicates if the challenge resource verification should be disabled. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret, String managedIdentity, boolean disableChallengeResourceVerification) { LOGGER.log(INFO, "Using Azure Key Vault: {0}", keyVaultUri); this.keyVaultUri = addTrailingSlashIfRequired(validateUri(keyVaultUri, "Azure Key Vault URI")); String domainNameSuffix = Optional.of(this.keyVaultUri) .map(uri -> uri.split("\\.", 2)[1]) .map(suffix -> suffix.substring(0, suffix.length() - 1)) .orElse(null); this.keyVaultBaseUri = HTTPS_PREFIX + domainNameSuffix; this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.managedIdentity = managedIdentity; this.disableChallengeResourceVerification = disableChallengeResourceVerification; } public static KeyVaultClient createKeyVaultClientBySystemProperty() { String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenant-id"); String clientId = System.getProperty("azure.keyvault.client-id"); String clientSecret = System.getProperty("azure.keyvault.client-secret"); String managedIdentity = System.getProperty("azure.keyvault.managed-identity"); boolean disableChallengeResourceVerification = Boolean.parseBoolean(System.getProperty("azure.keyvault.disable-challenge-resource-verification")); return new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret, managedIdentity, disableChallengeResourceVerification); } /** * Get the access token. * * @return The access token. */ private String getAccessToken() { if (accessToken != null && !accessToken.isExpired()) { return accessToken.getAccessToken(); } accessToken = getAccessTokenByHttpRequest(); return accessToken.getAccessToken(); } /** * Get the access token. * * @return The access token. */ private AccessToken getAccessTokenByHttpRequest() { LOGGER.entering("KeyVaultClient", "getAccessTokenByHttpRequest"); AccessToken accessToken = null; try { String resource = URLEncoder.encode(keyVaultBaseUri, "UTF-8"); if (managedIdentity != null) { managedIdentity = URLEncoder.encode(managedIdentity, "UTF-8"); } if (tenantId != null && clientId != null && clientSecret != null) { String aadAuthenticationUri = getLoginUri(keyVaultUri + "certificates" + API_VERSION_POSTFIX, disableChallengeResourceVerification); accessToken = AccessTokenUtil.getAccessToken(resource, aadAuthenticationUri, tenantId, clientId, clientSecret); } else { accessToken = AccessTokenUtil.getAccessToken(resource, managedIdentity); } } catch (Throwable t) { LOGGER.log(WARNING, "Could not obtain access token to authenticate with.", t); } LOGGER.exiting("KeyVaultClient", "getAccessTokenByHttpRequest", accessToken); return accessToken; } /** * Get the list of aliases. * * @return The list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates" + API_VERSION_POSTFIX; while (uri != null && !uri.isEmpty()) { String response = HttpUtil.get(uri, headers); CertificateListResult certificateListResult = null; if (response != null) { certificateListResult = (CertificateListResult) JsonConverterUtil.fromJson(response, CertificateListResult.class); } if (certificateListResult != null) { uri = certificateListResult.getNextLink(); for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } else { uri = null; } } return result; } /** * Get the certificate bundle. * * @param alias The alias. * @return The certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response != null) { result = (CertificateBundle) JsonConverterUtil.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias The alias. * * @return The certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateString))); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the certificate chain. * * @param alias The alias. * * @return The certificate chain, or null if not found. */ /** * Get the key. * * @param alias The alias. * @param password The password. * * @return The key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::isExportable) .orElse(false); String keyType = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::getKty) .orElse(null); if (!isExportable) { LOGGER.exiting("KeyVaultClient", "getKey", null); String keyType2 = keyType.contains("-HSM") ? keyType.substring(0, keyType.indexOf("-HSM")) : keyType; return Optional.ofNullable(certificateBundle) .map(CertificateBundle::getKid) .map(kid -> new KeyVaultPrivateKey(keyType2, kid, this)) .orElse(null); } String certificateSecretUri = certificateBundle.getSid(); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = HttpUtil.get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body == null) { LOGGER.exiting("KeyVaultClient", "getKey", null); return null; } Key key = null; SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(body, SecretBundle.class); String contentType = secretBundle.getContentType(); if ("application/x-pkcs12".equals(contentType)) { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray()); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException e) { LOGGER.log(WARNING, "Unable to decode key", e); } } else if ("application/x-pem-file".equals(contentType)) { try { key = createPrivateKeyFromPem(secretBundle.getValue(), keyType); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } /** * Get signature by Key Vault. * * @param digestName Digest name. * @param digestValue Digest value. * @param keyId The key ID. * * @return Signature. */ public byte[] getSignedWithPrivateKey(String digestName, String digestValue, String keyId) { SignResult result = null; String bodyString = String.format("{\"alg\": \"" + digestName + "\", \"value\": \"%s\"}", digestValue); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyId + "/sign" + API_VERSION_POSTFIX; String response = HttpUtil.post(uri, headers, bodyString, "application/json"); if (response != null) { result = (SignResult) JsonConverterUtil.fromJson(response, SignResult.class); } if (result != null) { return Base64.getUrlDecoder().decode(result.getValue()); } return new byte[0]; } /** * Get the private key from the PEM string. * * @param pemString The PEM file in string format. * @param keyType The private key type in string format. * * @return The private key. * * @throws IOException when an I/O error occurs. * @throws NoSuchAlgorithmException when algorithm is unavailable. * @throws InvalidKeySpecException when the private key cannot be generated. */ private PrivateKey createPrivateKeyFromPem(String pemString, String keyType) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new StringReader(pemString))) { String line = reader.readLine(); if (line == null || !line.contains("BEGIN PRIVATE KEY")) { throw new IllegalArgumentException("No PRIVATE KEY found"); } line = ""; while (line != null) { if (line.contains("END PRIVATE KEY")) { break; } builder.append(line); line = reader.readLine(); } } byte[] bytes = Base64.getDecoder().decode(builder.toString()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(keyType); return factory.generatePrivate(spec); } }
class KeyVaultClient { private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the Key Vault cloud URI. */ private final String keyVaultBaseUri; /** * Stores the Azure Key Vault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private final String tenantId; /** * Stores the client ID. */ private final String clientId; /** * Stores the client secret. */ private final String clientSecret; /** * Stores the managed identity (either the user-assigned managed identity object ID or null if system-assigned). */ private String managedIdentity; /** * Stores the token. */ private AccessToken accessToken; /** * Stores a flag indicating if challenge resource verification shall be disabled. */ private final boolean disableChallengeResourceVerification; /** * Constructor for authentication with user-assigned managed identity. * * @param keyVaultUri The Azure Key Vault URI. * @param managedIdentity The user-assigned managed identity object ID. */ KeyVaultClient(String keyVaultUri, String managedIdentity) { this(keyVaultUri, null, null, null, managedIdentity, false); } /** * Constructor for authentication with service principal. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret) { this(keyVaultUri, tenantId, clientId, clientSecret, null, false); } /** * Constructor. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. * @param managedIdentity The user-assigned managed identity object ID. * @param disableChallengeResourceVerification Indicates if the challenge resource verification should be disabled. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret, String managedIdentity, boolean disableChallengeResourceVerification) { LOGGER.log(INFO, "Using Azure Key Vault: {0}", keyVaultUri); this.keyVaultUri = addTrailingSlashIfRequired(validateUri(keyVaultUri, "Azure Key Vault URI")); String domainNameSuffix = Optional.of(this.keyVaultUri) .map(uri -> uri.split("\\.", 2)[1]) .map(suffix -> suffix.substring(0, suffix.length() - 1)) .orElse(null); this.keyVaultBaseUri = HTTPS_PREFIX + domainNameSuffix; this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.managedIdentity = managedIdentity; this.disableChallengeResourceVerification = disableChallengeResourceVerification; } public static KeyVaultClient createKeyVaultClientBySystemProperty() { String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenant-id"); String clientId = System.getProperty("azure.keyvault.client-id"); String clientSecret = System.getProperty("azure.keyvault.client-secret"); String managedIdentity = System.getProperty("azure.keyvault.managed-identity"); boolean disableChallengeResourceVerification = Boolean.parseBoolean(System.getProperty("azure.keyvault.disable-challenge-resource-verification")); return new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret, managedIdentity, disableChallengeResourceVerification); } /** * Get the access token. * * @return The access token. */ private String getAccessToken() { if (accessToken != null && !accessToken.isExpired()) { return accessToken.getAccessToken(); } accessToken = getAccessTokenByHttpRequest(); return accessToken.getAccessToken(); } /** * Get the access token. * * @return The access token. */ private AccessToken getAccessTokenByHttpRequest() { LOGGER.entering("KeyVaultClient", "getAccessTokenByHttpRequest"); AccessToken accessToken = null; try { String resource = URLEncoder.encode(keyVaultBaseUri, "UTF-8"); if (managedIdentity != null) { managedIdentity = URLEncoder.encode(managedIdentity, "UTF-8"); } if (tenantId != null && clientId != null && clientSecret != null) { String aadAuthenticationUri = getLoginUri(keyVaultUri + "certificates" + API_VERSION_POSTFIX, disableChallengeResourceVerification); accessToken = AccessTokenUtil.getAccessToken(resource, aadAuthenticationUri, tenantId, clientId, clientSecret); } else { accessToken = AccessTokenUtil.getAccessToken(resource, managedIdentity); } } catch (Throwable t) { LOGGER.log(WARNING, "Could not obtain access token to authenticate with.", t); } LOGGER.exiting("KeyVaultClient", "getAccessTokenByHttpRequest", accessToken); return accessToken; } /** * Get the list of aliases. * * @return The list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates" + API_VERSION_POSTFIX; while (uri != null && !uri.isEmpty()) { String response = HttpUtil.get(uri, headers); CertificateListResult certificateListResult = null; if (response != null) { certificateListResult = (CertificateListResult) JsonConverterUtil.fromJson(response, CertificateListResult.class); } if (certificateListResult != null) { uri = certificateListResult.getNextLink(); for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } else { uri = null; } } return result; } /** * Get the certificate bundle. * * @param alias The alias. * @return The certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response != null) { result = (CertificateBundle) JsonConverterUtil.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias The alias. * * @return The certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateString))); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the certificate chain. * * @param alias The alias. * * @return The certificate chain, or null if not found. */ /** * Get the key. * * @param alias The alias. * @param password The password. * * @return The key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::isExportable) .orElse(false); String keyType = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::getKty) .orElse(null); if (!isExportable) { LOGGER.exiting("KeyVaultClient", "getKey", null); String keyType2 = keyType.contains("-HSM") ? keyType.substring(0, keyType.indexOf("-HSM")) : keyType; return Optional.ofNullable(certificateBundle) .map(CertificateBundle::getKid) .map(kid -> new KeyVaultPrivateKey(keyType2, kid, this)) .orElse(null); } String certificateSecretUri = certificateBundle.getSid(); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = HttpUtil.get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body == null) { LOGGER.exiting("KeyVaultClient", "getKey", null); return null; } Key key = null; SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(body, SecretBundle.class); String contentType = secretBundle.getContentType(); if ("application/x-pkcs12".equals(contentType)) { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray()); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException e) { LOGGER.log(WARNING, "Unable to decode key", e); } } else if ("application/x-pem-file".equals(contentType)) { try { key = createPrivateKeyFromPem(secretBundle.getValue(), keyType); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } /** * Get signature by Key Vault. * * @param digestName Digest name. * @param digestValue Digest value. * @param keyId The key ID. * * @return Signature. */ public byte[] getSignedWithPrivateKey(String digestName, String digestValue, String keyId) { SignResult result = null; String bodyString = String.format("{\"alg\": \"" + digestName + "\", \"value\": \"%s\"}", digestValue); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyId + "/sign" + API_VERSION_POSTFIX; String response = HttpUtil.post(uri, headers, bodyString, "application/json"); if (response != null) { result = (SignResult) JsonConverterUtil.fromJson(response, SignResult.class); } if (result != null) { return Base64.getUrlDecoder().decode(result.getValue()); } return new byte[0]; } /** * Get the private key from the PEM string. * * @param pemString The PEM file in string format. * @param keyType The private key type in string format. * * @return The private key. * * @throws IOException when an I/O error occurs. * @throws NoSuchAlgorithmException when algorithm is unavailable. * @throws InvalidKeySpecException when the private key cannot be generated. */ private PrivateKey createPrivateKeyFromPem(String pemString, String keyType) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new StringReader(pemString))) { String line = reader.readLine(); if (line == null || !line.contains("BEGIN PRIVATE KEY")) { throw new IllegalArgumentException("No PRIVATE KEY found"); } line = ""; while (line != null) { if (line.contains("END PRIVATE KEY")) { break; } builder.append(line); line = reader.readLine(); } } byte[] bytes = Base64.getDecoder().decode(builder.toString()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(keyType); return factory.generatePrivate(spec); } }
To provide the stack trace when it is null.
public Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultClient", "getCertificateChain", alias); LOGGER.log(INFO, "Getting certificate chain for alias: {0}", alias); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "secrets/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response == null) { throw new NullPointerException(); } SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(response, SecretBundle.class); Certificate[] certificates = new Certificate[0]; try { certificates = loadCertificatesFromSecretBundleValue(secretBundle.getValue()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | PKCSException e) { LOGGER.log(WARNING, "Unable to decode certificate chain", e); } LOGGER.exiting("KeyVaultClient", "getCertificate", alias); return certificates; }
}
public Certificate[] getCertificateChain(String alias) { LOGGER.entering("KeyVaultClient", "getCertificateChain", alias); LOGGER.log(INFO, "Getting certificate chain for alias: {0}", alias); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "secrets/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response == null) { throw new NullPointerException(); } SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(response, SecretBundle.class); Certificate[] certificates = new Certificate[0]; try { certificates = loadCertificatesFromSecretBundleValue(secretBundle.getValue()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | PKCSException e) { LOGGER.log(WARNING, "Unable to decode certificate chain", e); } LOGGER.exiting("KeyVaultClient", "getCertificate", alias); return certificates; }
class KeyVaultClient { private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the Key Vault cloud URI. */ private final String keyVaultBaseUri; /** * Stores the Azure Key Vault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private final String tenantId; /** * Stores the client ID. */ private final String clientId; /** * Stores the client secret. */ private final String clientSecret; /** * Stores the managed identity (either the user-assigned managed identity object ID or null if system-assigned). */ private String managedIdentity; /** * Stores the token. */ private AccessToken accessToken; /** * Stores a flag indicating if challenge resource verification shall be disabled. */ private final boolean disableChallengeResourceVerification; /** * Constructor for authentication with user-assigned managed identity. * * @param keyVaultUri The Azure Key Vault URI. * @param managedIdentity The user-assigned managed identity object ID. */ KeyVaultClient(String keyVaultUri, String managedIdentity) { this(keyVaultUri, null, null, null, managedIdentity, false); } /** * Constructor for authentication with service principal. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret) { this(keyVaultUri, tenantId, clientId, clientSecret, null, false); } /** * Constructor. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. * @param managedIdentity The user-assigned managed identity object ID. * @param disableChallengeResourceVerification Indicates if the challenge resource verification should be disabled. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret, String managedIdentity, boolean disableChallengeResourceVerification) { LOGGER.log(INFO, "Using Azure Key Vault: {0}", keyVaultUri); this.keyVaultUri = addTrailingSlashIfRequired(validateUri(keyVaultUri, "Azure Key Vault URI")); String domainNameSuffix = Optional.of(this.keyVaultUri) .map(uri -> uri.split("\\.", 2)[1]) .map(suffix -> suffix.substring(0, suffix.length() - 1)) .orElse(null); this.keyVaultBaseUri = HTTPS_PREFIX + domainNameSuffix; this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.managedIdentity = managedIdentity; this.disableChallengeResourceVerification = disableChallengeResourceVerification; } public static KeyVaultClient createKeyVaultClientBySystemProperty() { String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenant-id"); String clientId = System.getProperty("azure.keyvault.client-id"); String clientSecret = System.getProperty("azure.keyvault.client-secret"); String managedIdentity = System.getProperty("azure.keyvault.managed-identity"); boolean disableChallengeResourceVerification = Boolean.parseBoolean(System.getProperty("azure.keyvault.disable-challenge-resource-verification")); return new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret, managedIdentity, disableChallengeResourceVerification); } /** * Get the access token. * * @return The access token. */ private String getAccessToken() { if (accessToken != null && !accessToken.isExpired()) { return accessToken.getAccessToken(); } accessToken = getAccessTokenByHttpRequest(); return accessToken.getAccessToken(); } /** * Get the access token. * * @return The access token. */ private AccessToken getAccessTokenByHttpRequest() { LOGGER.entering("KeyVaultClient", "getAccessTokenByHttpRequest"); AccessToken accessToken = null; try { String resource = URLEncoder.encode(keyVaultBaseUri, "UTF-8"); if (managedIdentity != null) { managedIdentity = URLEncoder.encode(managedIdentity, "UTF-8"); } if (tenantId != null && clientId != null && clientSecret != null) { String aadAuthenticationUri = getLoginUri(keyVaultUri + "certificates" + API_VERSION_POSTFIX, disableChallengeResourceVerification); accessToken = AccessTokenUtil.getAccessToken(resource, aadAuthenticationUri, tenantId, clientId, clientSecret); } else { accessToken = AccessTokenUtil.getAccessToken(resource, managedIdentity); } } catch (Throwable t) { LOGGER.log(WARNING, "Could not obtain access token to authenticate with.", t); } LOGGER.exiting("KeyVaultClient", "getAccessTokenByHttpRequest", accessToken); return accessToken; } /** * Get the list of aliases. * * @return The list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates" + API_VERSION_POSTFIX; while (uri != null && !uri.isEmpty()) { String response = HttpUtil.get(uri, headers); CertificateListResult certificateListResult = null; if (response != null) { certificateListResult = (CertificateListResult) JsonConverterUtil.fromJson(response, CertificateListResult.class); } if (certificateListResult != null) { uri = certificateListResult.getNextLink(); for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } else { uri = null; } } return result; } /** * Get the certificate bundle. * * @param alias The alias. * @return The certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response != null) { result = (CertificateBundle) JsonConverterUtil.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias The alias. * * @return The certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateString))); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the certificate chain. * * @param alias The alias. * * @return The certificate chain, or null if not found. */ /** * Get the key. * * @param alias The alias. * @param password The password. * * @return The key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::isExportable) .orElse(false); String keyType = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::getKty) .orElse(null); if (!isExportable) { LOGGER.exiting("KeyVaultClient", "getKey", null); String keyType2 = keyType.contains("-HSM") ? keyType.substring(0, keyType.indexOf("-HSM")) : keyType; return Optional.ofNullable(certificateBundle) .map(CertificateBundle::getKid) .map(kid -> new KeyVaultPrivateKey(keyType2, kid, this)) .orElse(null); } String certificateSecretUri = certificateBundle.getSid(); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = HttpUtil.get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body == null) { LOGGER.exiting("KeyVaultClient", "getKey", null); return null; } Key key = null; SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(body, SecretBundle.class); String contentType = secretBundle.getContentType(); if ("application/x-pkcs12".equals(contentType)) { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray()); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException e) { LOGGER.log(WARNING, "Unable to decode key", e); } } else if ("application/x-pem-file".equals(contentType)) { try { key = createPrivateKeyFromPem(secretBundle.getValue(), keyType); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } /** * Get signature by Key Vault. * * @param digestName Digest name. * @param digestValue Digest value. * @param keyId The key ID. * * @return Signature. */ public byte[] getSignedWithPrivateKey(String digestName, String digestValue, String keyId) { SignResult result = null; String bodyString = String.format("{\"alg\": \"" + digestName + "\", \"value\": \"%s\"}", digestValue); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyId + "/sign" + API_VERSION_POSTFIX; String response = HttpUtil.post(uri, headers, bodyString, "application/json"); if (response != null) { result = (SignResult) JsonConverterUtil.fromJson(response, SignResult.class); } if (result != null) { return Base64.getUrlDecoder().decode(result.getValue()); } return new byte[0]; } /** * Get the private key from the PEM string. * * @param pemString The PEM file in string format. * @param keyType The private key type in string format. * * @return The private key. * * @throws IOException when an I/O error occurs. * @throws NoSuchAlgorithmException when algorithm is unavailable. * @throws InvalidKeySpecException when the private key cannot be generated. */ private PrivateKey createPrivateKeyFromPem(String pemString, String keyType) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new StringReader(pemString))) { String line = reader.readLine(); if (line == null || !line.contains("BEGIN PRIVATE KEY")) { throw new IllegalArgumentException("No PRIVATE KEY found"); } line = ""; while (line != null) { if (line.contains("END PRIVATE KEY")) { break; } builder.append(line); line = reader.readLine(); } } byte[] bytes = Base64.getDecoder().decode(builder.toString()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(keyType); return factory.generatePrivate(spec); } }
class KeyVaultClient { private static final Logger LOGGER = Logger.getLogger(KeyVaultClient.class.getName()); /** * Stores the Key Vault cloud URI. */ private final String keyVaultBaseUri; /** * Stores the Azure Key Vault URI. */ private final String keyVaultUri; /** * Stores the tenant ID. */ private final String tenantId; /** * Stores the client ID. */ private final String clientId; /** * Stores the client secret. */ private final String clientSecret; /** * Stores the managed identity (either the user-assigned managed identity object ID or null if system-assigned). */ private String managedIdentity; /** * Stores the token. */ private AccessToken accessToken; /** * Stores a flag indicating if challenge resource verification shall be disabled. */ private final boolean disableChallengeResourceVerification; /** * Constructor for authentication with user-assigned managed identity. * * @param keyVaultUri The Azure Key Vault URI. * @param managedIdentity The user-assigned managed identity object ID. */ KeyVaultClient(String keyVaultUri, String managedIdentity) { this(keyVaultUri, null, null, null, managedIdentity, false); } /** * Constructor for authentication with service principal. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret) { this(keyVaultUri, tenantId, clientId, clientSecret, null, false); } /** * Constructor. * * @param keyVaultUri The Azure Key Vault URI. * @param tenantId The tenant ID. * @param clientId The client ID. * @param clientSecret The client secret. * @param managedIdentity The user-assigned managed identity object ID. * @param disableChallengeResourceVerification Indicates if the challenge resource verification should be disabled. */ public KeyVaultClient(String keyVaultUri, String tenantId, String clientId, String clientSecret, String managedIdentity, boolean disableChallengeResourceVerification) { LOGGER.log(INFO, "Using Azure Key Vault: {0}", keyVaultUri); this.keyVaultUri = addTrailingSlashIfRequired(validateUri(keyVaultUri, "Azure Key Vault URI")); String domainNameSuffix = Optional.of(this.keyVaultUri) .map(uri -> uri.split("\\.", 2)[1]) .map(suffix -> suffix.substring(0, suffix.length() - 1)) .orElse(null); this.keyVaultBaseUri = HTTPS_PREFIX + domainNameSuffix; this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.managedIdentity = managedIdentity; this.disableChallengeResourceVerification = disableChallengeResourceVerification; } public static KeyVaultClient createKeyVaultClientBySystemProperty() { String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenant-id"); String clientId = System.getProperty("azure.keyvault.client-id"); String clientSecret = System.getProperty("azure.keyvault.client-secret"); String managedIdentity = System.getProperty("azure.keyvault.managed-identity"); boolean disableChallengeResourceVerification = Boolean.parseBoolean(System.getProperty("azure.keyvault.disable-challenge-resource-verification")); return new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret, managedIdentity, disableChallengeResourceVerification); } /** * Get the access token. * * @return The access token. */ private String getAccessToken() { if (accessToken != null && !accessToken.isExpired()) { return accessToken.getAccessToken(); } accessToken = getAccessTokenByHttpRequest(); return accessToken.getAccessToken(); } /** * Get the access token. * * @return The access token. */ private AccessToken getAccessTokenByHttpRequest() { LOGGER.entering("KeyVaultClient", "getAccessTokenByHttpRequest"); AccessToken accessToken = null; try { String resource = URLEncoder.encode(keyVaultBaseUri, "UTF-8"); if (managedIdentity != null) { managedIdentity = URLEncoder.encode(managedIdentity, "UTF-8"); } if (tenantId != null && clientId != null && clientSecret != null) { String aadAuthenticationUri = getLoginUri(keyVaultUri + "certificates" + API_VERSION_POSTFIX, disableChallengeResourceVerification); accessToken = AccessTokenUtil.getAccessToken(resource, aadAuthenticationUri, tenantId, clientId, clientSecret); } else { accessToken = AccessTokenUtil.getAccessToken(resource, managedIdentity); } } catch (Throwable t) { LOGGER.log(WARNING, "Could not obtain access token to authenticate with.", t); } LOGGER.exiting("KeyVaultClient", "getAccessTokenByHttpRequest", accessToken); return accessToken; } /** * Get the list of aliases. * * @return The list of aliases. */ public List<String> getAliases() { ArrayList<String> result = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates" + API_VERSION_POSTFIX; while (uri != null && !uri.isEmpty()) { String response = HttpUtil.get(uri, headers); CertificateListResult certificateListResult = null; if (response != null) { certificateListResult = (CertificateListResult) JsonConverterUtil.fromJson(response, CertificateListResult.class); } if (certificateListResult != null) { uri = certificateListResult.getNextLink(); for (CertificateItem certificateItem : certificateListResult.getValue()) { String id = certificateItem.getId(); String alias = id.substring(id.indexOf("certificates") + "certificates".length() + 1); result.add(alias); } } else { uri = null; } } return result; } /** * Get the certificate bundle. * * @param alias The alias. * @return The certificate bundle. */ private CertificateBundle getCertificateBundle(String alias) { CertificateBundle result = null; HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyVaultUri + "certificates/" + alias + API_VERSION_POSTFIX; String response = HttpUtil.get(uri, headers); if (response != null) { result = (CertificateBundle) JsonConverterUtil.fromJson(response, CertificateBundle.class); } return result; } /** * Get the certificate. * * @param alias The alias. * * @return The certificate, or null if not found. */ public Certificate getCertificate(String alias) { LOGGER.entering("KeyVaultClient", "getCertificate", alias); LOGGER.log(INFO, "Getting certificate for alias: {0}", alias); X509Certificate certificate = null; CertificateBundle certificateBundle = getCertificateBundle(alias); if (certificateBundle != null) { String certificateString = certificateBundle.getCer(); if (certificateString != null) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.getDecoder().decode(certificateString))); } catch (CertificateException ce) { LOGGER.log(WARNING, "Certificate error", ce); } } } LOGGER.exiting("KeyVaultClient", "getCertificate", certificate); return certificate; } /** * Get the certificate chain. * * @param alias The alias. * * @return The certificate chain, or null if not found. */ /** * Get the key. * * @param alias The alias. * @param password The password. * * @return The key. */ public Key getKey(String alias, char[] password) { LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password }); LOGGER.log(INFO, "Getting key for alias: {0}", alias); CertificateBundle certificateBundle = getCertificateBundle(alias); boolean isExportable = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::isExportable) .orElse(false); String keyType = Optional.ofNullable(certificateBundle) .map(CertificateBundle::getPolicy) .map(CertificatePolicy::getKeyProperties) .map(KeyProperties::getKty) .orElse(null); if (!isExportable) { LOGGER.exiting("KeyVaultClient", "getKey", null); String keyType2 = keyType.contains("-HSM") ? keyType.substring(0, keyType.indexOf("-HSM")) : keyType; return Optional.ofNullable(certificateBundle) .map(CertificateBundle::getKid) .map(kid -> new KeyVaultPrivateKey(keyType2, kid, this)) .orElse(null); } String certificateSecretUri = certificateBundle.getSid(); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String body = HttpUtil.get(certificateSecretUri + API_VERSION_POSTFIX, headers); if (body == null) { LOGGER.exiting("KeyVaultClient", "getKey", null); return null; } Key key = null; SecretBundle secretBundle = (SecretBundle) JsonConverterUtil.fromJson(body, SecretBundle.class); String contentType = secretBundle.getContentType(); if ("application/x-pkcs12".equals(contentType)) { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load( new ByteArrayInputStream(Base64.getDecoder().decode(secretBundle.getValue())), "".toCharArray()); alias = keyStore.aliases().nextElement(); key = keyStore.getKey(alias, "".toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException e) { LOGGER.log(WARNING, "Unable to decode key", e); } } else if ("application/x-pem-file".equals(contentType)) { try { key = createPrivateKeyFromPem(secretBundle.getValue(), keyType); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ex) { LOGGER.log(WARNING, "Unable to decode key", ex); } } LOGGER.exiting("KeyVaultClient", "getKey", key); return key; } /** * Get signature by Key Vault. * * @param digestName Digest name. * @param digestValue Digest value. * @param keyId The key ID. * * @return Signature. */ public byte[] getSignedWithPrivateKey(String digestName, String digestValue, String keyId) { SignResult result = null; String bodyString = String.format("{\"alg\": \"" + digestName + "\", \"value\": \"%s\"}", digestValue); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + getAccessToken()); String uri = keyId + "/sign" + API_VERSION_POSTFIX; String response = HttpUtil.post(uri, headers, bodyString, "application/json"); if (response != null) { result = (SignResult) JsonConverterUtil.fromJson(response, SignResult.class); } if (result != null) { return Base64.getUrlDecoder().decode(result.getValue()); } return new byte[0]; } /** * Get the private key from the PEM string. * * @param pemString The PEM file in string format. * @param keyType The private key type in string format. * * @return The private key. * * @throws IOException when an I/O error occurs. * @throws NoSuchAlgorithmException when algorithm is unavailable. * @throws InvalidKeySpecException when the private key cannot be generated. */ private PrivateKey createPrivateKeyFromPem(String pemString, String keyType) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new StringReader(pemString))) { String line = reader.readLine(); if (line == null || !line.contains("BEGIN PRIVATE KEY")) { throw new IllegalArgumentException("No PRIVATE KEY found"); } line = ""; while (line != null) { if (line.contains("END PRIVATE KEY")) { break; } builder.append(line); line = reader.readLine(); } } byte[] bytes = Base64.getDecoder().decode(builder.toString()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(keyType); return factory.generatePrivate(spec); } }
`pushDeploy` branches on tier. For non-Flex, it calls zipDeploy For Flex, it calls oneDeploy There is actually another branching for ConsumptionPlan (non-Flex) that CLI uses "WEBSITE_RUN_FROM_PACKAGE"
public Mono<KuduDeploymentResult> pushDeployAsync(DeployType type, File file, DeployOptions deployOptions) { if (type != DeployType.ZIP) { return Mono.error(new IllegalArgumentException("Deployment to Function App supports ZIP package.")); } return getAppServicePlanIsFlexConsumptionMono().flatMap(appServiceIsFlexConsumptionPlan -> { try { if (appServiceIsFlexConsumptionPlan) { return kuduClient.pushDeployFlexConsumptionAsync(file); } else { return kuduClient.pushZipDeployAsync(file) .then(Mono.just(new KuduDeploymentResult("latest"))); } } catch (IOException e) { return Mono.error(e); } }); }
}
public Mono<KuduDeploymentResult> pushDeployAsync(DeployType type, File file, DeployOptions deployOptions) { if (type != DeployType.ZIP) { return Mono.error(new IllegalArgumentException("Deployment to Function App supports ZIP package.")); } return getAppServicePlanIsFlexConsumptionMono().flatMap(appServiceIsFlexConsumptionPlan -> { try { if (appServiceIsFlexConsumptionPlan) { return kuduClient.pushDeployFlexConsumptionAsync(file); } else { return kuduClient.pushZipDeployAsync(file) .then(Mono.just(new KuduDeploymentResult("latest"))); } } catch (IOException e) { return Mono.error(e); } }); }
class FunctionAppImpl extends AppServiceBaseImpl< FunctionApp, FunctionAppImpl, FunctionApp.DefinitionStages.WithCreate, FunctionApp.Update> implements FunctionApp, FunctionApp.Definition, FunctionApp.DefinitionStages.NewAppServicePlanWithGroup, FunctionApp.DefinitionStages.ExistingLinuxPlanWithGroup, FunctionApp.Update { private static final ClientLogger LOGGER = new ClientLogger(FunctionAppImpl.class); private static final String SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String SETTING_WEBSITE_CONTENTSHARE = "WEBSITE_CONTENTSHARE"; private static final String SETTING_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String SETTING_WEB_JOBS_DASHBOARD = "AzureWebJobsDashboard"; private Creatable<StorageAccount> storageAccountCreatable; private StorageAccount storageAccountToSet; private StorageAccount currentStorageAccount; private FunctionService functionService; private FunctionDeploymentSlots deploymentSlots; private String functionServiceHost; private Boolean appServicePlanIsFlexConsumption; FunctionAppImpl( final String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); if (!isInCreateMode()) { initializeFunctionService(); } } private void initializeFunctionService() { if (functionService == null) { UrlBuilder urlBuilder = UrlBuilder.parse(this.defaultHostname()); String baseUrl; if (urlBuilder.getScheme() == null) { urlBuilder.setScheme("https"); } try { baseUrl = urlBuilder.toUrl().toString(); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0, count = manager().httpPipeline().getPolicyCount(); i < count; ++i) { HttpPipelinePolicy policy = manager().httpPipeline().getPolicy(i); if (!(policy instanceof AuthenticationPolicy) && !(policy instanceof ProviderRegistrationPolicy) && !(policy instanceof AuxiliaryAuthenticationPolicy)) { policies.add(policy); } } policies.add(new FunctionAuthenticationPolicy(this)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(manager().httpPipeline().getHttpClient()) .build(); functionServiceHost = baseUrl; functionService = RestProxy.create(FunctionService.class, httpPipeline, SerializerFactory.createDefaultManagementSerializerAdapter()); } } @Override public void setInner(SiteInner innerObject) { super.setInner(innerObject); } @Override public FunctionDeploymentSlots deploymentSlots() { if (deploymentSlots == null) { deploymentSlots = new FunctionDeploymentSlotsImpl(this); } return deploymentSlots; } @Override public FunctionAppImpl withNewConsumptionPlan() { return withNewAppServicePlan(OperatingSystem.WINDOWS, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withNewConsumptionPlan(String appServicePlanName) { return withNewAppServicePlan( appServicePlanName, OperatingSystem.WINDOWS, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withRuntime(String runtime) { return withAppSetting(SETTING_FUNCTIONS_WORKER_RUNTIME, runtime); } @Override public FunctionAppImpl withRuntimeVersion(String version) { return withAppSetting(SETTING_FUNCTIONS_EXTENSION_VERSION, version.startsWith("~") ? version : "~" + version); } @Override public FunctionAppImpl withLatestRuntimeVersion() { return withRuntimeVersion("latest"); } @Override Mono<SiteInner> submitSite(SiteInner site) { if (isFunctionAppOnACA()) { return createOrUpdateInner(site); } else { return super.submitSite(site); } } @Override Mono<SiteInner> submitSite(SitePatchResourceInner siteUpdate) { if (isFunctionAppOnACA()) { return updateInner(siteUpdate); } else { return super.submitSite(siteUpdate); } } @Override Mono<Indexable> submitAppSettings() { if (storageAccountCreatable != null && this.taskResult(storageAccountCreatable.key()) != null) { storageAccountToSet = this.taskResult(storageAccountCreatable.key()); } if (storageAccountToSet == null) { return super.submitAppSettings(); } else { return storageAccountToSet .getKeysAsync() .flatMap(storageAccountKeys -> { StorageAccountKey key = storageAccountKeys.get(0); String connectionString = ResourceManagerUtils .getStorageConnectionString(storageAccountToSet.name(), key.value(), manager().environment()); addAppSettingIfNotModified(SETTING_WEB_JOBS_STORAGE, connectionString); if (!isFunctionAppOnACA()) { addAppSettingIfNotModified(SETTING_WEB_JOBS_DASHBOARD, connectionString); return this.manager().appServicePlans().getByIdAsync(this.appServicePlanId()) .flatMap(appServicePlan -> { if (appServicePlan == null || isConsumptionOrPremiumAppServicePlan(appServicePlan.pricingTier())) { addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, connectionString); addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTSHARE, this.manager().resourceManager().internalContext() .randomResourceName(name(), 32)); } return FunctionAppImpl.super.submitAppSettings(); }); } else { return FunctionAppImpl.super.submitAppSettings(); } }).then( Mono .fromCallable( () -> { currentStorageAccount = storageAccountToSet; storageAccountToSet = null; storageAccountCreatable = null; return this; })); } } @Override public OperatingSystem operatingSystem() { if (isFunctionAppOnACA()) { return OperatingSystem.LINUX; } return (innerModel().reserved() == null || !innerModel().reserved()) ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; } private void addAppSettingIfNotModified(String key, String value) { if (!appSettingModified(key)) { withAppSetting(key, value); } } private boolean appSettingModified(String key) { return (appSettingsToAdd != null && appSettingsToAdd.containsKey(key)) || (appSettingsToRemove != null && appSettingsToRemove.contains(key)); } private static boolean isConsumptionOrPremiumAppServicePlan(PricingTier pricingTier) { if (pricingTier == null || pricingTier.toSkuDescription() == null) { return true; } SkuDescription description = pricingTier.toSkuDescription(); return SkuName.DYNAMIC.toString().equalsIgnoreCase(description.tier()) || SkuName.ELASTIC_PREMIUM.toString().equalsIgnoreCase(description.tier()); } @Override FunctionAppImpl withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) { return super.withNewAppServicePlan(operatingSystem, pricingTier).autoSetAlwaysOn(pricingTier); } @Override FunctionAppImpl withNewAppServicePlan( String appServicePlan, OperatingSystem operatingSystem, PricingTier pricingTier) { return super.withNewAppServicePlan(appServicePlan, operatingSystem, pricingTier).autoSetAlwaysOn(pricingTier); } @Override public FunctionAppImpl withExistingAppServicePlan(AppServicePlan appServicePlan) { super.withExistingAppServicePlan(appServicePlan); return autoSetAlwaysOn(appServicePlan.pricingTier()); } private FunctionAppImpl autoSetAlwaysOn(PricingTier pricingTier) { SkuDescription description = pricingTier.toSkuDescription(); if (description.tier().equalsIgnoreCase(SkuName.FREE.toString()) || description.tier().equalsIgnoreCase(SkuName.SHARED.toString()) || description.tier().equalsIgnoreCase(SkuName.DYNAMIC.toString()) || description.tier().equalsIgnoreCase(SkuName.ELASTIC_PREMIUM.toString()) || description.tier().equalsIgnoreCase(SkuName.ELASTIC_ISOLATED.toString())) { return withWebAppAlwaysOn(false); } else { return withWebAppAlwaysOn(true); } } @Override public FunctionAppImpl withNewStorageAccount(String name, StorageAccountSkuType sku) { StorageAccount.DefinitionStages.WithGroup storageDefine = manager().storageManager().storageAccounts().define(name).withRegion(regionName()); if (super.creatableGroup != null && isInCreateMode()) { storageAccountCreatable = storageDefine .withNewResourceGroup(super.creatableGroup) .withGeneralPurposeAccountKindV2() .withSku(sku); } else { storageAccountCreatable = storageDefine .withExistingResourceGroup(resourceGroupName()) .withGeneralPurposeAccountKindV2() .withSku(sku); } this.addDependency(storageAccountCreatable); return this; } @Override public FunctionAppImpl withNewStorageAccount(Creatable<StorageAccount> storageAccount) { storageAccountCreatable = storageAccount; this.addDependency(storageAccountCreatable); return this; } @Override public FunctionAppImpl withExistingStorageAccount(StorageAccount storageAccount) { this.storageAccountToSet = storageAccount; return this; } @Override public FunctionAppImpl withDailyUsageQuota(int quota) { innerModel().withDailyMemoryTimeQuota(quota); return this; } @Override public FunctionAppImpl withoutDailyUsageQuota() { return withDailyUsageQuota(0); } @Override public FunctionAppImpl withNewLinuxConsumptionPlan() { return withNewAppServicePlan(OperatingSystem.LINUX, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withNewLinuxConsumptionPlan(String appServicePlanName) { return withNewAppServicePlan( appServicePlanName, OperatingSystem.LINUX, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withNewLinuxAppServicePlan(PricingTier pricingTier) { return super.withNewAppServicePlan(OperatingSystem.LINUX, pricingTier); } @Override public FunctionAppImpl withNewLinuxAppServicePlan(String appServicePlanName, PricingTier pricingTier) { return super.withNewAppServicePlan(appServicePlanName, OperatingSystem.LINUX, pricingTier); } @Override public FunctionAppImpl withNewLinuxAppServicePlan(Creatable<AppServicePlan> appServicePlanCreatable) { super.withNewAppServicePlan(appServicePlanCreatable); if (appServicePlanCreatable instanceof AppServicePlan) { this.autoSetAlwaysOn(((AppServicePlan) appServicePlanCreatable).pricingTier()); } return this; } @Override public FunctionAppImpl withExistingLinuxAppServicePlan(AppServicePlan appServicePlan) { return super.withExistingAppServicePlan(appServicePlan).autoSetAlwaysOn(appServicePlan.pricingTier()); } @Override public FunctionAppImpl withBuiltInImage(final FunctionRuntimeStack runtimeStack) { ensureLinuxPlan(); cleanUpContainerSettings(); if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } withRuntime(runtimeStack.runtime()); withRuntimeVersion(runtimeStack.version()); siteConfig.withLinuxFxVersion(runtimeStack.getLinuxFxVersion()); return this; } @Override public FunctionAppImpl withPublicDockerHubImage(String imageAndTag) { ensureLinuxPlan(); return super.withPublicDockerHubImage(imageAndTag); } @Override public FunctionAppImpl withPrivateDockerHubImage(String imageAndTag) { ensureLinuxPlan(); return super.withPublicDockerHubImage(imageAndTag); } @Override public FunctionAppImpl withPrivateRegistryImage(String imageAndTag, String serverUrl) { ensureLinuxPlan(); super.withPrivateRegistryImage(imageAndTag, serverUrl); if (isFunctionAppOnACA()) { try { URL url = new URL(serverUrl); withAppSetting(SETTING_REGISTRY_SERVER, url.getAuthority() + url.getFile()); } catch (MalformedURLException e) { } } return this; } @Override protected void cleanUpContainerSettings() { if (siteConfig != null && siteConfig.linuxFxVersion() != null) { siteConfig.withLinuxFxVersion(null); } if (siteConfig != null && siteConfig.windowsFxVersion() != null) { siteConfig.withWindowsFxVersion(null); } withoutAppSetting(SETTING_DOCKER_IMAGE); withoutAppSetting(SETTING_REGISTRY_SERVER); withoutAppSetting(SETTING_REGISTRY_USERNAME); withoutAppSetting(SETTING_REGISTRY_PASSWORD); } @Override protected OperatingSystem appServicePlanOperatingSystem(AppServicePlan appServicePlan) { return (appServicePlan.innerModel().reserved() == null || !appServicePlan.innerModel().reserved()) ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; } @Override public StorageAccount storageAccount() { return currentStorageAccount; } @Override public String getMasterKey() { return getMasterKeyAsync().block(); } @Override public Mono<String> getMasterKeyAsync() { return this.manager().serviceClient().getWebApps().listHostKeysAsync(resourceGroupName(), name()) .map(HostKeysInner::masterKey); } @Override public PagedIterable<FunctionEnvelope> listFunctions() { return this.manager().functionApps().listFunctions(resourceGroupName(), name()); } @Override public Map<String, String> listFunctionKeys(String functionName) { return listFunctionKeysAsync(functionName).block(); } @Override public Mono<Map<String, String>> listFunctionKeysAsync(final String functionName) { return functionService .listFunctionKeys(functionServiceHost, functionName) .map( result -> { Map<String, String> keys = new HashMap<>(); if (result.keys != null) { for (NameValuePair pair : result.keys) { keys.put(pair.name(), pair.value()); } } return keys; }); } @Override public NameValuePair addFunctionKey(String functionName, String keyName, String keyValue) { return addFunctionKeyAsync(functionName, keyName, keyValue).block(); } @Override public Mono<NameValuePair> addFunctionKeyAsync(String functionName, String keyName, String keyValue) { if (keyValue != null) { return functionService .addFunctionKey( functionServiceHost, functionName, keyName, new NameValuePair().withName(keyName).withValue(keyValue)); } else { return functionService.generateFunctionKey(functionServiceHost, functionName, keyName); } } @Override public void removeFunctionKey(String functionName, String keyName) { removeFunctionKeyAsync(functionName, keyName).block(); } @Override public Mono<Void> removeFunctionKeyAsync(String functionName, String keyName) { return functionService.deleteFunctionKey(functionServiceHost, functionName, keyName); } @Override public void triggerFunction(String functionName, Object payload) { triggerFunctionAsync(functionName, payload).block(); } @Override public Mono<Void> triggerFunctionAsync(String functionName, Object payload) { return functionService.triggerFunction(functionServiceHost, functionName, payload); } @Override public void syncTriggers() { syncTriggersAsync().block(); } @Override public Mono<Void> syncTriggersAsync() { return manager() .serviceClient() .getWebApps() .syncFunctionTriggersAsync(resourceGroupName(), name()) .onErrorResume( throwable -> { if (throwable instanceof ManagementException && ((ManagementException) throwable).getResponse().getStatusCode() == 200) { return Mono.empty(); } else { return Mono.error(throwable); } }); } @Override public String managedEnvironmentId() { return innerModel().managedEnvironmentId(); } @Override public Integer maxReplicas() { if (this.siteConfig == null) { return null; } return this.siteConfig.functionAppScaleLimit(); } @Override public Integer minReplicas() { if (this.siteConfig == null) { return null; } return this.siteConfig.minimumElasticInstanceCount(); } @Override public Flux<String> streamApplicationLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamApplicationLogsAsync()); } @Override public Flux<String> streamHttpLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamHttpLogsAsync()); } @Override public Flux<String> streamTraceLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamTraceLogsAsync()); } @Override public Flux<String> streamDeploymentLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamDeploymentLogsAsync()); } @Override public Flux<String> streamAllLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamAllLogsAsync()); } @Override public Mono<Void> zipDeployAsync(File zipFile) { try { return kuduClient.zipDeployAsync(zipFile); } catch (IOException e) { return Mono.error(e); } } @Override public void zipDeploy(File zipFile) { zipDeployAsync(zipFile).block(); } @Override public Mono<Void> zipDeployAsync(InputStream zipFile, long length) { return kuduClient.zipDeployAsync(zipFile, length); } @Override public void zipDeploy(InputStream zipFile, long length) { zipDeployAsync(zipFile, length).block(); } @Override public void beforeGroupCreateOrUpdate() { if (isFunctionAppOnACA()) { adaptForFunctionAppOnACA(); } super.beforeGroupCreateOrUpdate(); } private void adaptForFunctionAppOnACA() { this.innerModel().withReserved(null); if (this.siteConfig != null) { SiteConfigInner siteConfigInner = new SiteConfigInner(); siteConfigInner.withLinuxFxVersion(this.siteConfig.linuxFxVersion()); siteConfigInner.withMinimumElasticInstanceCount(this.siteConfig.minimumElasticInstanceCount()); siteConfigInner.withFunctionAppScaleLimit(this.siteConfig.functionAppScaleLimit()); siteConfigInner.withAppSettings(this.siteConfig.appSettings() == null ? new ArrayList<>() : this.siteConfig.appSettings()); if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) { for (String settingToRemove : appSettingsToRemove) { siteConfigInner.appSettings().removeIf(kvPair -> Objects.equals(settingToRemove, kvPair.name())); } for (Map.Entry<String, String> entry : appSettingsToAdd.entrySet()) { siteConfigInner.appSettings().add(new NameValuePair().withName(entry.getKey()).withValue(entry.getValue())); } } this.innerModel().withSiteConfig(siteConfigInner); } } @Override public Mono<FunctionApp> createAsync() { if (this.isInCreateMode()) { if (innerModel().serverFarmId() == null && !isFunctionAppOnACA()) { withNewConsumptionPlan(); } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( this.manager().resourceManager().internalContext() .randomResourceName(getStorageAccountName(), 20), StorageAccountSkuType.STANDARD_LRS); } } return super.createAsync(); } @Override public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) { if (!isGroupFaulted) { initializeFunctionService(); } return super.afterPostRunAsync(isGroupFaulted); } @Override public FunctionAppImpl withManagedEnvironmentId(String managedEnvironmentId) { this.innerModel().withManagedEnvironmentId(managedEnvironmentId); if (!CoreUtils.isNullOrEmpty(managedEnvironmentId)) { this.innerModel().withKind("functionapp,linux,container,azurecontainerapps"); if (this.siteConfig == null) { this.siteConfig = new SiteConfigResourceInner().withAppSettings(new ArrayList<>()); } } return this; } @Override public FunctionAppImpl withMaxReplicas(int maxReplicas) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withFunctionAppScaleLimit(maxReplicas); return this; } @Override public FunctionAppImpl withMinReplicas(int minReplicas) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withMinimumElasticInstanceCount(minReplicas); return this; } @Override public Mono<Map<String, AppSetting>> getAppSettingsAsync() { if (isFunctionAppOnACA()) { return listAppSettings() .map( appSettingsInner -> appSettingsInner .properties() .entrySet() .stream() .collect( Collectors .toMap( Map.Entry::getKey, entry -> new AppSettingImpl( entry.getKey(), entry.getValue(), false)))); } else { return super.getAppSettingsAsync(); } } /** * Whether this Function App is on Azure Container Apps environment. * * @return whether this Function App is on Azure Container Apps environment */ boolean isFunctionAppOnACA() { return isFunctionAppOnACA(innerModel()); } static boolean isFunctionAppOnACA(SiteInner siteInner) { return siteInner != null && !CoreUtils.isNullOrEmpty(siteInner.managedEnvironmentId()); } @Override Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) { Mono<SiteInner> updateInner = super.updateInner(siteUpdate); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(updateInner); } else { return updateInner; } } @Override Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) { Mono<SiteConfigResourceInner> createOrUpdateSiteConfig = super.createOrUpdateSiteConfig(siteConfig); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(createOrUpdateSiteConfig); } else { return createOrUpdateSiteConfig; } } @Override Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) { Mono<StringDictionaryInner> updateAppSettings = super.updateAppSettings(inner); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(updateAppSettings); } else { return updateAppSettings; } } @Override Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) { Mono<ConnectionStringDictionaryInner> updateConnectionStrings = super.updateConnectionStrings(inner); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(updateConnectionStrings); } else { return updateConnectionStrings; } } @Override public void deploy(DeployType type, File file) { deployAsync(type, file).block(); } @Override public Mono<Void> deployAsync(DeployType type, File file) { return deployAsync(type, file, null); } @Override public void deploy(DeployType type, File file, DeployOptions deployOptions) { deployAsync(type, file, null).block(); } @Override public Mono<Void> deployAsync(DeployType type, File file, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, null) .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override public void deploy(DeployType type, InputStream file, long length) { deployAsync(type, file, length).block(); } @Override public Mono<Void> deployAsync(DeployType type, InputStream file, long length) { return deployAsync(type, file, length, null); } @Override public void deploy(DeployType type, InputStream file, long length, DeployOptions deployOptions) { deployAsync(type, file, length, null).block(); } @Override public Mono<Void> deployAsync(DeployType type, InputStream file, long length, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, length, null) .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override public KuduDeploymentResult pushDeploy(DeployType type, File file, DeployOptions deployOptions) { return pushDeployAsync(type, file, deployOptions).block(); } @Override private Mono<KuduDeploymentResult> pushDeployAsync(DeployType type, InputStream file, long length, DeployOptions deployOptions) { if (type != DeployType.ZIP) { return Mono.error(new IllegalArgumentException("Deployment to Function App supports ZIP package.")); } return getAppServicePlanIsFlexConsumptionMono().flatMap(appServiceIsFlexConsumptionPlan -> { try { if (appServiceIsFlexConsumptionPlan) { return kuduClient.pushDeployFlexConsumptionAsync(file, length); } else { return kuduClient.pushZipDeployAsync(file, length) .then(Mono.just(new KuduDeploymentResult("latest"))); } } catch (IOException e) { return Mono.error(e); } }); } private Mono<Boolean> getAppServicePlanIsFlexConsumptionMono() { Mono<Boolean> updateAppServicePlan = Mono.justOrEmpty(appServicePlanIsFlexConsumption); if (appServicePlanIsFlexConsumption == null) { updateAppServicePlan = Mono.defer( () -> manager().appServicePlans() .getByIdAsync(this.appServicePlanId()) .map(appServicePlan -> { appServicePlanIsFlexConsumption = "FlexConsumption".equals(appServicePlan.pricingTier().toSkuDescription().tier()); return appServicePlanIsFlexConsumption; })); } return updateAppServicePlan; } @Override public CsmDeploymentStatus getDeploymentStatus(String deploymentId) { return getDeploymentStatusAsync(deploymentId).block(); } @Override public Mono<CsmDeploymentStatus> getDeploymentStatusAsync(String deploymentId) { SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); return this.manager().serviceClient().getWebApps() .getProductionSiteDeploymentStatusWithResponseAsync(this.resourceGroupName(), this.name(), deploymentId) .flatMap(fluxResponse -> { HttpResponse response = new HttpFluxBBResponse(fluxResponse); return response.getBodyAsString() .flatMap(bodyString -> { CsmDeploymentStatus status; try { status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.error(new ManagementException("Deserialize failed for response body.", response)); } return Mono.justOrEmpty(status); }).doFinally(ignored -> response.close()); }); } @Host("{$host}") @ServiceInterface(name = "FunctionService") private interface FunctionService { @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Get("admin/functions/{name}/keys") Mono<FunctionKeyListResult> listFunctionKeys( @HostParam("$host") String host, @PathParam("name") String functionName); @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Put("admin/functions/{name}/keys/{keyName}") Mono<NameValuePair> addFunctionKey( @HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName, @BodyParam("application/json") NameValuePair key); @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Post("admin/functions/{name}/keys/{keyName}") Mono<NameValuePair> generateFunctionKey( @HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Delete("admin/functions/{name}/keys/{keyName}") Mono<Void> deleteFunctionKey( @HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Post("admin/host/ping") Mono<Void> ping(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Get("admin/host/status") Mono<Void> getHostStatus(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Post("admin/functions/{name}") Mono<Void> triggerFunction( @HostParam("$host") String host, @PathParam("name") String functionName, @BodyParam("application/json") Object payload); } private static class FunctionKeyListResult implements JsonSerializable<FunctionKeyListResult> { private List<NameValuePair> keys; @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { return jsonWriter .writeStartObject() .writeArrayField("keys", keys, JsonWriter::writeJson) .writeEndObject(); } public static FunctionKeyListResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { FunctionKeyListResult result = new FunctionKeyListResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("keys".equals(fieldName)) { List<NameValuePair> keys = reader.readArray(reader1 -> reader1.readObject(NameValuePair::fromJson)); result.keys = keys; } else { reader.skipChildren(); } } return result; }); } } private String getStorageAccountName() { return name().replaceAll("[^a-zA-Z0-9]", ""); } }
class FunctionAppImpl extends AppServiceBaseImpl< FunctionApp, FunctionAppImpl, FunctionApp.DefinitionStages.WithCreate, FunctionApp.Update> implements FunctionApp, FunctionApp.Definition, FunctionApp.DefinitionStages.NewAppServicePlanWithGroup, FunctionApp.DefinitionStages.ExistingLinuxPlanWithGroup, FunctionApp.Update { private static final ClientLogger LOGGER = new ClientLogger(FunctionAppImpl.class); private static final String SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"; private static final String SETTING_WEBSITE_CONTENTSHARE = "WEBSITE_CONTENTSHARE"; private static final String SETTING_WEB_JOBS_STORAGE = "AzureWebJobsStorage"; private static final String SETTING_WEB_JOBS_DASHBOARD = "AzureWebJobsDashboard"; private Creatable<StorageAccount> storageAccountCreatable; private StorageAccount storageAccountToSet; private StorageAccount currentStorageAccount; private FunctionService functionService; private FunctionDeploymentSlots deploymentSlots; private String functionServiceHost; private Boolean appServicePlanIsFlexConsumption; FunctionAppImpl( final String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); if (!isInCreateMode()) { initializeFunctionService(); } } private void initializeFunctionService() { if (functionService == null) { UrlBuilder urlBuilder = UrlBuilder.parse(this.defaultHostname()); String baseUrl; if (urlBuilder.getScheme() == null) { urlBuilder.setScheme("https"); } try { baseUrl = urlBuilder.toUrl().toString(); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } List<HttpPipelinePolicy> policies = new ArrayList<>(); for (int i = 0, count = manager().httpPipeline().getPolicyCount(); i < count; ++i) { HttpPipelinePolicy policy = manager().httpPipeline().getPolicy(i); if (!(policy instanceof AuthenticationPolicy) && !(policy instanceof ProviderRegistrationPolicy) && !(policy instanceof AuxiliaryAuthenticationPolicy)) { policies.add(policy); } } policies.add(new FunctionAuthenticationPolicy(this)); HttpPipeline httpPipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(manager().httpPipeline().getHttpClient()) .build(); functionServiceHost = baseUrl; functionService = RestProxy.create(FunctionService.class, httpPipeline, SerializerFactory.createDefaultManagementSerializerAdapter()); } } @Override public void setInner(SiteInner innerObject) { super.setInner(innerObject); } @Override public FunctionDeploymentSlots deploymentSlots() { if (deploymentSlots == null) { deploymentSlots = new FunctionDeploymentSlotsImpl(this); } return deploymentSlots; } @Override public FunctionAppImpl withNewConsumptionPlan() { return withNewAppServicePlan(OperatingSystem.WINDOWS, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withNewConsumptionPlan(String appServicePlanName) { return withNewAppServicePlan( appServicePlanName, OperatingSystem.WINDOWS, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withRuntime(String runtime) { return withAppSetting(SETTING_FUNCTIONS_WORKER_RUNTIME, runtime); } @Override public FunctionAppImpl withRuntimeVersion(String version) { return withAppSetting(SETTING_FUNCTIONS_EXTENSION_VERSION, version.startsWith("~") ? version : "~" + version); } @Override public FunctionAppImpl withLatestRuntimeVersion() { return withRuntimeVersion("latest"); } @Override Mono<SiteInner> submitSite(SiteInner site) { if (isFunctionAppOnACA()) { return createOrUpdateInner(site); } else { return super.submitSite(site); } } @Override Mono<SiteInner> submitSite(SitePatchResourceInner siteUpdate) { if (isFunctionAppOnACA()) { return updateInner(siteUpdate); } else { return super.submitSite(siteUpdate); } } @Override Mono<Indexable> submitAppSettings() { if (storageAccountCreatable != null && this.taskResult(storageAccountCreatable.key()) != null) { storageAccountToSet = this.taskResult(storageAccountCreatable.key()); } if (storageAccountToSet == null) { return super.submitAppSettings(); } else { return storageAccountToSet .getKeysAsync() .flatMap(storageAccountKeys -> { StorageAccountKey key = storageAccountKeys.get(0); String connectionString = ResourceManagerUtils .getStorageConnectionString(storageAccountToSet.name(), key.value(), manager().environment()); addAppSettingIfNotModified(SETTING_WEB_JOBS_STORAGE, connectionString); if (!isFunctionAppOnACA()) { addAppSettingIfNotModified(SETTING_WEB_JOBS_DASHBOARD, connectionString); return this.manager().appServicePlans().getByIdAsync(this.appServicePlanId()) .flatMap(appServicePlan -> { if (appServicePlan == null || isConsumptionOrPremiumAppServicePlan(appServicePlan.pricingTier())) { addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, connectionString); addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTSHARE, this.manager().resourceManager().internalContext() .randomResourceName(name(), 32)); } return FunctionAppImpl.super.submitAppSettings(); }); } else { return FunctionAppImpl.super.submitAppSettings(); } }).then( Mono .fromCallable( () -> { currentStorageAccount = storageAccountToSet; storageAccountToSet = null; storageAccountCreatable = null; return this; })); } } @Override public OperatingSystem operatingSystem() { if (isFunctionAppOnACA()) { return OperatingSystem.LINUX; } return (innerModel().reserved() == null || !innerModel().reserved()) ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; } private void addAppSettingIfNotModified(String key, String value) { if (!appSettingModified(key)) { withAppSetting(key, value); } } private boolean appSettingModified(String key) { return (appSettingsToAdd != null && appSettingsToAdd.containsKey(key)) || (appSettingsToRemove != null && appSettingsToRemove.contains(key)); } private static boolean isConsumptionOrPremiumAppServicePlan(PricingTier pricingTier) { if (pricingTier == null || pricingTier.toSkuDescription() == null) { return true; } SkuDescription description = pricingTier.toSkuDescription(); return SkuName.DYNAMIC.toString().equalsIgnoreCase(description.tier()) || SkuName.ELASTIC_PREMIUM.toString().equalsIgnoreCase(description.tier()); } @Override FunctionAppImpl withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) { return super.withNewAppServicePlan(operatingSystem, pricingTier).autoSetAlwaysOn(pricingTier); } @Override FunctionAppImpl withNewAppServicePlan( String appServicePlan, OperatingSystem operatingSystem, PricingTier pricingTier) { return super.withNewAppServicePlan(appServicePlan, operatingSystem, pricingTier).autoSetAlwaysOn(pricingTier); } @Override public FunctionAppImpl withExistingAppServicePlan(AppServicePlan appServicePlan) { super.withExistingAppServicePlan(appServicePlan); return autoSetAlwaysOn(appServicePlan.pricingTier()); } private FunctionAppImpl autoSetAlwaysOn(PricingTier pricingTier) { SkuDescription description = pricingTier.toSkuDescription(); if (description.tier().equalsIgnoreCase(SkuName.FREE.toString()) || description.tier().equalsIgnoreCase(SkuName.SHARED.toString()) || description.tier().equalsIgnoreCase(SkuName.DYNAMIC.toString()) || description.tier().equalsIgnoreCase(SkuName.ELASTIC_PREMIUM.toString()) || description.tier().equalsIgnoreCase(SkuName.ELASTIC_ISOLATED.toString())) { return withWebAppAlwaysOn(false); } else { return withWebAppAlwaysOn(true); } } @Override public FunctionAppImpl withNewStorageAccount(String name, StorageAccountSkuType sku) { StorageAccount.DefinitionStages.WithGroup storageDefine = manager().storageManager().storageAccounts().define(name).withRegion(regionName()); if (super.creatableGroup != null && isInCreateMode()) { storageAccountCreatable = storageDefine .withNewResourceGroup(super.creatableGroup) .withGeneralPurposeAccountKindV2() .withSku(sku); } else { storageAccountCreatable = storageDefine .withExistingResourceGroup(resourceGroupName()) .withGeneralPurposeAccountKindV2() .withSku(sku); } this.addDependency(storageAccountCreatable); return this; } @Override public FunctionAppImpl withNewStorageAccount(Creatable<StorageAccount> storageAccount) { storageAccountCreatable = storageAccount; this.addDependency(storageAccountCreatable); return this; } @Override public FunctionAppImpl withExistingStorageAccount(StorageAccount storageAccount) { this.storageAccountToSet = storageAccount; return this; } @Override public FunctionAppImpl withDailyUsageQuota(int quota) { innerModel().withDailyMemoryTimeQuota(quota); return this; } @Override public FunctionAppImpl withoutDailyUsageQuota() { return withDailyUsageQuota(0); } @Override public FunctionAppImpl withNewLinuxConsumptionPlan() { return withNewAppServicePlan(OperatingSystem.LINUX, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withNewLinuxConsumptionPlan(String appServicePlanName) { return withNewAppServicePlan( appServicePlanName, OperatingSystem.LINUX, new PricingTier(SkuName.DYNAMIC.toString(), "Y1")); } @Override public FunctionAppImpl withNewLinuxAppServicePlan(PricingTier pricingTier) { return super.withNewAppServicePlan(OperatingSystem.LINUX, pricingTier); } @Override public FunctionAppImpl withNewLinuxAppServicePlan(String appServicePlanName, PricingTier pricingTier) { return super.withNewAppServicePlan(appServicePlanName, OperatingSystem.LINUX, pricingTier); } @Override public FunctionAppImpl withNewLinuxAppServicePlan(Creatable<AppServicePlan> appServicePlanCreatable) { super.withNewAppServicePlan(appServicePlanCreatable); if (appServicePlanCreatable instanceof AppServicePlan) { this.autoSetAlwaysOn(((AppServicePlan) appServicePlanCreatable).pricingTier()); } return this; } @Override public FunctionAppImpl withExistingLinuxAppServicePlan(AppServicePlan appServicePlan) { return super.withExistingAppServicePlan(appServicePlan).autoSetAlwaysOn(appServicePlan.pricingTier()); } @Override public FunctionAppImpl withBuiltInImage(final FunctionRuntimeStack runtimeStack) { ensureLinuxPlan(); cleanUpContainerSettings(); if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } withRuntime(runtimeStack.runtime()); withRuntimeVersion(runtimeStack.version()); siteConfig.withLinuxFxVersion(runtimeStack.getLinuxFxVersion()); return this; } @Override public FunctionAppImpl withPublicDockerHubImage(String imageAndTag) { ensureLinuxPlan(); return super.withPublicDockerHubImage(imageAndTag); } @Override public FunctionAppImpl withPrivateDockerHubImage(String imageAndTag) { ensureLinuxPlan(); return super.withPublicDockerHubImage(imageAndTag); } @Override public FunctionAppImpl withPrivateRegistryImage(String imageAndTag, String serverUrl) { ensureLinuxPlan(); super.withPrivateRegistryImage(imageAndTag, serverUrl); if (isFunctionAppOnACA()) { try { URL url = new URL(serverUrl); withAppSetting(SETTING_REGISTRY_SERVER, url.getAuthority() + url.getFile()); } catch (MalformedURLException e) { } } return this; } @Override protected void cleanUpContainerSettings() { if (siteConfig != null && siteConfig.linuxFxVersion() != null) { siteConfig.withLinuxFxVersion(null); } if (siteConfig != null && siteConfig.windowsFxVersion() != null) { siteConfig.withWindowsFxVersion(null); } withoutAppSetting(SETTING_DOCKER_IMAGE); withoutAppSetting(SETTING_REGISTRY_SERVER); withoutAppSetting(SETTING_REGISTRY_USERNAME); withoutAppSetting(SETTING_REGISTRY_PASSWORD); } @Override protected OperatingSystem appServicePlanOperatingSystem(AppServicePlan appServicePlan) { return (appServicePlan.innerModel().reserved() == null || !appServicePlan.innerModel().reserved()) ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; } @Override public StorageAccount storageAccount() { return currentStorageAccount; } @Override public String getMasterKey() { return getMasterKeyAsync().block(); } @Override public Mono<String> getMasterKeyAsync() { return this.manager().serviceClient().getWebApps().listHostKeysAsync(resourceGroupName(), name()) .map(HostKeysInner::masterKey); } @Override public PagedIterable<FunctionEnvelope> listFunctions() { return this.manager().functionApps().listFunctions(resourceGroupName(), name()); } @Override public Map<String, String> listFunctionKeys(String functionName) { return listFunctionKeysAsync(functionName).block(); } @Override public Mono<Map<String, String>> listFunctionKeysAsync(final String functionName) { return functionService .listFunctionKeys(functionServiceHost, functionName) .map( result -> { Map<String, String> keys = new HashMap<>(); if (result.keys != null) { for (NameValuePair pair : result.keys) { keys.put(pair.name(), pair.value()); } } return keys; }); } @Override public NameValuePair addFunctionKey(String functionName, String keyName, String keyValue) { return addFunctionKeyAsync(functionName, keyName, keyValue).block(); } @Override public Mono<NameValuePair> addFunctionKeyAsync(String functionName, String keyName, String keyValue) { if (keyValue != null) { return functionService .addFunctionKey( functionServiceHost, functionName, keyName, new NameValuePair().withName(keyName).withValue(keyValue)); } else { return functionService.generateFunctionKey(functionServiceHost, functionName, keyName); } } @Override public void removeFunctionKey(String functionName, String keyName) { removeFunctionKeyAsync(functionName, keyName).block(); } @Override public Mono<Void> removeFunctionKeyAsync(String functionName, String keyName) { return functionService.deleteFunctionKey(functionServiceHost, functionName, keyName); } @Override public void triggerFunction(String functionName, Object payload) { triggerFunctionAsync(functionName, payload).block(); } @Override public Mono<Void> triggerFunctionAsync(String functionName, Object payload) { return functionService.triggerFunction(functionServiceHost, functionName, payload); } @Override public void syncTriggers() { syncTriggersAsync().block(); } @Override public Mono<Void> syncTriggersAsync() { return manager() .serviceClient() .getWebApps() .syncFunctionTriggersAsync(resourceGroupName(), name()) .onErrorResume( throwable -> { if (throwable instanceof ManagementException && ((ManagementException) throwable).getResponse().getStatusCode() == 200) { return Mono.empty(); } else { return Mono.error(throwable); } }); } @Override public String managedEnvironmentId() { return innerModel().managedEnvironmentId(); } @Override public Integer maxReplicas() { if (this.siteConfig == null) { return null; } return this.siteConfig.functionAppScaleLimit(); } @Override public Integer minReplicas() { if (this.siteConfig == null) { return null; } return this.siteConfig.minimumElasticInstanceCount(); } @Override public Flux<String> streamApplicationLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamApplicationLogsAsync()); } @Override public Flux<String> streamHttpLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamHttpLogsAsync()); } @Override public Flux<String> streamTraceLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamTraceLogsAsync()); } @Override public Flux<String> streamDeploymentLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamDeploymentLogsAsync()); } @Override public Flux<String> streamAllLogsAsync() { return functionService .ping(functionServiceHost) .then(functionService.getHostStatus(functionServiceHost)) .thenMany(FunctionAppImpl.super.streamAllLogsAsync()); } @Override public Mono<Void> zipDeployAsync(File zipFile) { try { return kuduClient.zipDeployAsync(zipFile); } catch (IOException e) { return Mono.error(e); } } @Override public void zipDeploy(File zipFile) { zipDeployAsync(zipFile).block(); } @Override public Mono<Void> zipDeployAsync(InputStream zipFile, long length) { return kuduClient.zipDeployAsync(zipFile, length); } @Override public void zipDeploy(InputStream zipFile, long length) { zipDeployAsync(zipFile, length).block(); } @Override public void beforeGroupCreateOrUpdate() { if (isFunctionAppOnACA()) { adaptForFunctionAppOnACA(); } super.beforeGroupCreateOrUpdate(); } private void adaptForFunctionAppOnACA() { this.innerModel().withReserved(null); if (this.siteConfig != null) { SiteConfigInner siteConfigInner = new SiteConfigInner(); siteConfigInner.withLinuxFxVersion(this.siteConfig.linuxFxVersion()); siteConfigInner.withMinimumElasticInstanceCount(this.siteConfig.minimumElasticInstanceCount()); siteConfigInner.withFunctionAppScaleLimit(this.siteConfig.functionAppScaleLimit()); siteConfigInner.withAppSettings(this.siteConfig.appSettings() == null ? new ArrayList<>() : this.siteConfig.appSettings()); if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) { for (String settingToRemove : appSettingsToRemove) { siteConfigInner.appSettings().removeIf(kvPair -> Objects.equals(settingToRemove, kvPair.name())); } for (Map.Entry<String, String> entry : appSettingsToAdd.entrySet()) { siteConfigInner.appSettings().add(new NameValuePair().withName(entry.getKey()).withValue(entry.getValue())); } } this.innerModel().withSiteConfig(siteConfigInner); } } @Override public Mono<FunctionApp> createAsync() { if (this.isInCreateMode()) { if (innerModel().serverFarmId() == null && !isFunctionAppOnACA()) { withNewConsumptionPlan(); } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( this.manager().resourceManager().internalContext() .randomResourceName(getStorageAccountName(), 20), StorageAccountSkuType.STANDARD_LRS); } } return super.createAsync(); } @Override public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) { if (!isGroupFaulted) { initializeFunctionService(); } return super.afterPostRunAsync(isGroupFaulted); } @Override public FunctionAppImpl withManagedEnvironmentId(String managedEnvironmentId) { this.innerModel().withManagedEnvironmentId(managedEnvironmentId); if (!CoreUtils.isNullOrEmpty(managedEnvironmentId)) { this.innerModel().withKind("functionapp,linux,container,azurecontainerapps"); if (this.siteConfig == null) { this.siteConfig = new SiteConfigResourceInner().withAppSettings(new ArrayList<>()); } } return this; } @Override public FunctionAppImpl withMaxReplicas(int maxReplicas) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withFunctionAppScaleLimit(maxReplicas); return this; } @Override public FunctionAppImpl withMinReplicas(int minReplicas) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withMinimumElasticInstanceCount(minReplicas); return this; } @Override public Mono<Map<String, AppSetting>> getAppSettingsAsync() { if (isFunctionAppOnACA()) { return listAppSettings() .map( appSettingsInner -> appSettingsInner .properties() .entrySet() .stream() .collect( Collectors .toMap( Map.Entry::getKey, entry -> new AppSettingImpl( entry.getKey(), entry.getValue(), false)))); } else { return super.getAppSettingsAsync(); } } /** * Whether this Function App is on Azure Container Apps environment. * * @return whether this Function App is on Azure Container Apps environment */ boolean isFunctionAppOnACA() { return isFunctionAppOnACA(innerModel()); } static boolean isFunctionAppOnACA(SiteInner siteInner) { return siteInner != null && !CoreUtils.isNullOrEmpty(siteInner.managedEnvironmentId()); } @Override Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) { Mono<SiteInner> updateInner = super.updateInner(siteUpdate); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(updateInner); } else { return updateInner; } } @Override Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) { Mono<SiteConfigResourceInner> createOrUpdateSiteConfig = super.createOrUpdateSiteConfig(siteConfig); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(createOrUpdateSiteConfig); } else { return createOrUpdateSiteConfig; } } @Override Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) { Mono<StringDictionaryInner> updateAppSettings = super.updateAppSettings(inner); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(updateAppSettings); } else { return updateAppSettings; } } @Override Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) { Mono<ConnectionStringDictionaryInner> updateConnectionStrings = super.updateConnectionStrings(inner); if (isFunctionAppOnACA()) { return RetryUtils.backoffRetryForFunctionAppAca(updateConnectionStrings); } else { return updateConnectionStrings; } } @Override public void deploy(DeployType type, File file) { deployAsync(type, file).block(); } @Override public Mono<Void> deployAsync(DeployType type, File file) { return deployAsync(type, file, null); } @Override public void deploy(DeployType type, File file, DeployOptions deployOptions) { deployAsync(type, file, null).block(); } @Override public Mono<Void> deployAsync(DeployType type, File file, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, null) .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override public void deploy(DeployType type, InputStream file, long length) { deployAsync(type, file, length).block(); } @Override public Mono<Void> deployAsync(DeployType type, InputStream file, long length) { return deployAsync(type, file, length, null); } @Override public void deploy(DeployType type, InputStream file, long length, DeployOptions deployOptions) { deployAsync(type, file, length, null).block(); } @Override public Mono<Void> deployAsync(DeployType type, InputStream file, long length, DeployOptions deployOptions) { return this.pushDeployAsync(type, file, length, null) .flatMap(result -> kuduClient.pollDeploymentStatus(result, manager().serviceClient().getDefaultPollInterval())); } @Override public KuduDeploymentResult pushDeploy(DeployType type, File file, DeployOptions deployOptions) { return pushDeployAsync(type, file, deployOptions).block(); } @Override private Mono<KuduDeploymentResult> pushDeployAsync(DeployType type, InputStream file, long length, DeployOptions deployOptions) { if (type != DeployType.ZIP) { return Mono.error(new IllegalArgumentException("Deployment to Function App supports ZIP package.")); } return getAppServicePlanIsFlexConsumptionMono().flatMap(appServiceIsFlexConsumptionPlan -> { try { if (appServiceIsFlexConsumptionPlan) { return kuduClient.pushDeployFlexConsumptionAsync(file, length); } else { return kuduClient.pushZipDeployAsync(file, length) .then(Mono.just(new KuduDeploymentResult("latest"))); } } catch (IOException e) { return Mono.error(e); } }); } private Mono<Boolean> getAppServicePlanIsFlexConsumptionMono() { Mono<Boolean> updateAppServicePlan = Mono.justOrEmpty(appServicePlanIsFlexConsumption); if (appServicePlanIsFlexConsumption == null) { updateAppServicePlan = Mono.defer( () -> manager().appServicePlans() .getByIdAsync(this.appServicePlanId()) .map(appServicePlan -> { appServicePlanIsFlexConsumption = "FlexConsumption".equals(appServicePlan.pricingTier().toSkuDescription().tier()); return appServicePlanIsFlexConsumption; })); } return updateAppServicePlan; } @Override public CsmDeploymentStatus getDeploymentStatus(String deploymentId) { return getDeploymentStatusAsync(deploymentId).block(); } @Override public Mono<CsmDeploymentStatus> getDeploymentStatusAsync(String deploymentId) { SerializerAdapter serializerAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); return this.manager().serviceClient().getWebApps() .getProductionSiteDeploymentStatusWithResponseAsync(this.resourceGroupName(), this.name(), deploymentId) .flatMap(fluxResponse -> { HttpResponse response = new HttpFluxBBResponse(fluxResponse); return response.getBodyAsString() .flatMap(bodyString -> { CsmDeploymentStatus status; try { status = serializerAdapter.deserialize(bodyString, CsmDeploymentStatus.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.error(new ManagementException("Deserialize failed for response body.", response)); } return Mono.justOrEmpty(status); }).doFinally(ignored -> response.close()); }); } @Host("{$host}") @ServiceInterface(name = "FunctionService") private interface FunctionService { @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Get("admin/functions/{name}/keys") Mono<FunctionKeyListResult> listFunctionKeys( @HostParam("$host") String host, @PathParam("name") String functionName); @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Put("admin/functions/{name}/keys/{keyName}") Mono<NameValuePair> addFunctionKey( @HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName, @BodyParam("application/json") NameValuePair key); @Headers({ "Accept: application/json", "Content-Type: application/json; charset=utf-8" }) @Post("admin/functions/{name}/keys/{keyName}") Mono<NameValuePair> generateFunctionKey( @HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Delete("admin/functions/{name}/keys/{keyName}") Mono<Void> deleteFunctionKey( @HostParam("$host") String host, @PathParam("name") String functionName, @PathParam("keyName") String keyName); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Post("admin/host/ping") Mono<Void> ping(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Get("admin/host/status") Mono<Void> getHostStatus(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8" }) @Post("admin/functions/{name}") Mono<Void> triggerFunction( @HostParam("$host") String host, @PathParam("name") String functionName, @BodyParam("application/json") Object payload); } private static class FunctionKeyListResult implements JsonSerializable<FunctionKeyListResult> { private List<NameValuePair> keys; @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { return jsonWriter .writeStartObject() .writeArrayField("keys", keys, JsonWriter::writeJson) .writeEndObject(); } public static FunctionKeyListResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { FunctionKeyListResult result = new FunctionKeyListResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("keys".equals(fieldName)) { List<NameValuePair> keys = reader.readArray(reader1 -> reader1.readObject(NameValuePair::fromJson)); result.keys = keys; } else { reader.skipChildren(); } } return result; }); } } private String getStorageAccountName() { return name().replaceAll("[^a-zA-Z0-9]", ""); } }
how do we verify there is only 1 query request per partition being sent to the backend? I think even without the change, this test might still pass
public void queryOrderByRoundTrips() { String query = "SELECT c.v FROM c where c.type='testing' order by c.v asc"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 5; CosmosPagedFlux<RoundTripDocument> queryObservable = roundTripsContainer.queryItems(query, options, RoundTripDocument.class); FeedResponse<RoundTripDocument> feedResponse = queryObservable.byPage(pageSize).take(1).blockFirst(); assertThat(feedResponse.getResults().size()).isEqualTo(5); for (RoundTripDocument roundTripDocument : feedResponse.getResults()) { assertThat(roundTripDocument.v).isEqualTo(3); } FeedResponseDiagnostics feedResponseDiagnostics = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor().getFeedResponseDiagnostics(feedResponse.getCosmosDiagnostics()); assertThat(feedResponseDiagnostics.getClientSideRequestStatistics().size()).isEqualTo(3); }
FeedResponse<RoundTripDocument> feedResponse = queryObservable.byPage(pageSize).take(1).blockFirst();
public void queryOrderByRoundTrips() { String query = "SELECT c.v FROM c where c.type='testing' order by c.v asc"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 5; for (int i = 0; i < 100; i++) { CosmosPagedFlux<RoundTripDocument> queryObservable = roundTripsContainer.queryItems(query, options, RoundTripDocument.class); FeedResponse<RoundTripDocument> feedResponse = queryObservable.byPage(pageSize).take(1).blockFirst(); assertThat(feedResponse.getResults().size()).isEqualTo(5); for (RoundTripDocument roundTripDocument : feedResponse.getResults()) { assertThat(roundTripDocument.v).isEqualTo(3); } Map<String, QueryMetrics> queryMetricsMap = ModelBridgeInternal.queryMetricsMap(feedResponse); List<QueryMetrics> queryMetrics = new ArrayList<>(queryMetricsMap.values()); for (QueryMetrics queryMetric : queryMetrics) { assertThat(queryMetric.getOutputDocumentCount()).isLessThanOrEqualTo(10); } FeedResponseDiagnostics feedResponseDiagnostics = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor().getFeedResponseDiagnostics(feedResponse.getCosmosDiagnostics()); assertThat(feedResponseDiagnostics.getClientSideRequestStatistics().size()).isLessThanOrEqualTo(4); } }
class OrderbyDocumentQueryTest extends TestSuiteBase { public static final String PROPTYPE = "proptype"; public static final String PROP_MIXED = "propMixed"; private final double minQueryRequestChargePerPartition = 2.0; private CosmosAsyncClient client; private CosmosAsyncContainer createdCollection; private CosmosAsyncContainer roundTripsContainer; private CosmosAsyncDatabase createdDatabase; private List<InternalObjectNode> createdDocuments = new ArrayList<>(); private int numberOfPartitions; @Factory(dataProvider = "clientBuildersWithDirect") public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContent() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @DataProvider(name = "sortOrder") public Object[][] sortOrder() { return new Object[][] { { "ASC" }, {"DESC"} }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderBy(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedResourceIds); } int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValue(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValueAndCustomFactoryMethod(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getImpl(options) .setCustomItemSerializer( new CosmosItemSerializerNoExceptionWrapping() { @Override public <T> Map<String, Object> serialize(T item) { return null; } @Override public <T> T deserialize(Map<String, Object> jsonNodeMap, Class<T> classType) { return (T)(jsonNodeMap.get("_value")); } }); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByInt() throws Exception { String query = "SELECT * FROM r where r.propInt != null ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByString() throws Exception { String query = "SELECT * FROM r where r.propStr != null ORDER BY r.propStr"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<String> validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propStr", d -> d.getString("propStr"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByMixedTypes(String sortOrder) throws Exception { List<PartitionKeyRange> partitionKeyRanges = getPartitionKeyRanges(createdCollection.getId(), BridgeInternal .getContextClient(this.client)); assertThat(partitionKeyRanges.size()).isGreaterThan(1); String query = "SELECT * FROM r ORDER BY r.propMixed "; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> sourceIds = createdDocuments.stream() .map(Resource::getId) .collect(Collectors.toList()); int pageSize = 20; CosmosPagedFlux<InternalObjectNode> queryFlux = createdCollection .queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryFlux.byPage(pageSize).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); List<InternalObjectNode> results = new ArrayList<>(); subscriber.values().forEach(feedResponse -> results.addAll(feedResponse.getResults())); assertThat(results.size()).isEqualTo(createdDocuments.size()); List<String> resultIds = results.stream().map(Resource::getId).collect(Collectors.toList()); assertThat(resultIds).containsExactlyInAnyOrderElementsOf(sourceIds); final List<String> typeList = Arrays.asList("undefined", "null", "boolean", "number", "string", "array", "object"); List<String> observedTypes = new ArrayList<>(); results.forEach(item -> { String propType = "undefined"; if (item.has(PROPTYPE)) { propType = item.getString(PROPTYPE); } if (!observedTypes.contains(propType)) { observedTypes.add(propType); } else { boolean equals = observedTypes.get(observedTypes.size() - 1).equals(propType); assertThat(equals).isTrue().as("Items of same type should be contiguous"); } }); assertThat(observedTypes).containsExactlyElementsOf(typeList); for (String type : typeList) { List<InternalObjectNode> items = results.stream().filter(r -> { if ("undefined".equals(type)) { return !r.has(PROPTYPE); } return type.equals(r.getString(PROPTYPE)); }).collect(Collectors.toList()); if ("boolean".equals(type)) { List<Boolean> sourceList = items.stream().map(n -> n.getBoolean(PROP_MIXED)).collect(Collectors.toList()); List<Boolean> toBeSortedList = new ArrayList<>(sourceList); toBeSortedList.sort(Comparator.comparing(Boolean::booleanValue)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } if ("number".equals(type)) { List<Number> numberList = items.stream().map(n -> (Number) n.get(PROP_MIXED)).collect(Collectors.toList()); List<Number> toBeSortedList = new ArrayList<>(numberList); Collections.copy(toBeSortedList, numberList); toBeSortedList.sort(Comparator.comparingDouble(Number::doubleValue)); assertThat(toBeSortedList).containsExactlyElementsOf(numberList); } if ("string".equals(type)) { List<String> sourceList = items.stream().map(n -> n.getString(PROP_MIXED)).collect(Collectors.toList()); List<String> toBeSortedList = new ArrayList<>(sourceList); Collections.copy(toBeSortedList, sourceList); toBeSortedList.sort(Comparator.comparing(String::valueOf)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } } } private List<PartitionKeyRange> getPartitionKeyRanges( String containerId, AsyncDocumentClient asyncDocumentClient) { List<PartitionKeyRange> partitionKeyRanges = new ArrayList<>(); List<FeedResponse<PartitionKeyRange>> partitionFeedResponseList = asyncDocumentClient .readPartitionKeyRanges("/dbs/" + createdDatabase.getId() + "/colls/" + containerId, new CosmosQueryRequestOptions()) .collectList().block(); partitionFeedResponseList.forEach(f -> partitionKeyRanges.addAll(f.getResults())); return partitionKeyRanges; } @DataProvider(name = "topValue") public Object[][] topValueParameter() { return new Object[][] { { 0 }, { 1 }, { 5 }, { createdDocuments.size() - 1 }, { createdDocuments.size() }, { createdDocuments.size() + 1 }, { 2 * createdDocuments.size() } }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "topValue") public void queryOrderWithTop(int topValue) throws Exception { String query = String.format("SELECT TOP %d * FROM r where r.propInt != null ORDER BY r.propInt", topValue); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator) .stream().limit(topValue).collect(Collectors.toList()); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * (topValue > 0 ? minQueryRequestChargePerPartition : 1)) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } private <T> List<String> sortDocumentsAndCollectResourceIds(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(Resource::getResourceId).collect(Collectors.toList()); } @SuppressWarnings("unchecked") private <T> List<T> sortDocumentsAndCollectValues(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(d -> (T)d.getMap().get(propName)) .collect(Collectors.toList()); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.propScopedPartitionInt ASC"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey("duplicatePartitionKeyValue")); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); int preferredPageSize = 3; TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryObservable.byPage(preferredPageSize).take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> page = (FeedResponse<InternalObjectNode>) subscriber.getEvents().get(0).get(0); assertThat(page.getResults()).hasSize(3); assertThat(page.getContinuationToken()).isNotEmpty(); queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<InternalObjectNode> expectedDocs = createdDocuments.stream() .filter(d -> (StringUtils.equals("duplicatePartitionKeyValue", d.getString("mypk")))) .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList()); int expectedPageSize = (expectedDocs.size() + preferredPageSize - 1) / preferredPageSize; assertThat(expectedDocs).hasSize(10 - 3); FeedResponseListValidator<InternalObjectNode> validator = null; validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(page.getContinuationToken(), preferredPageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void orderByContinuationTokenRoundTrip() throws Exception { { OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); String serialized = orderByContinuationToken.toString(); ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse(serialized, outOrderByContinuationToken)).isTrue(); OrderByContinuationToken deserialized = outOrderByContinuationToken.v; CompositeContinuationToken compositeContinuationToken = deserialized.getCompositeContinuationToken(); String token = compositeContinuationToken.getToken(); Range<String> range = compositeContinuationToken.getRange(); assertThat(token).isEqualTo("asdf"); assertThat(range.getMin()).isEqualTo("A"); assertThat(range.getMax()).isEqualTo("D"); assertThat(range.isMinInclusive()).isEqualTo(false); assertThat(range.isMaxInclusive()).isEqualTo(true); QueryItem[] orderByItems = deserialized.getOrderByItems(); assertThat(orderByItems).isNotNull(); assertThat(orderByItems.length).isEqualTo(1); assertThat(orderByItems[0].getItem()).isEqualTo(42); String rid = deserialized.getRid(); assertThat(rid).isEqualTo("rid"); boolean inclusive = deserialized.getInclusive(); assertThat(inclusive).isEqualTo(false); } { ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse("{\"property\" : \"Not a valid Order By Token\"}", outOrderByContinuationToken)).isFalse(); } } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); Comparator<Integer> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<Integer> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100}, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<String> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> validatorComparator; if(sortOrder.equals("ASC")) { validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); }else{ validatorComparator = Comparator.nullsFirst(Comparator.<String>reverseOrder()); } List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.assertInvalidContinuationToken(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByArray(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propArray != null ORDER BY r.propArray %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByObject(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propObject != null ORDER BY r.propObject %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } public InternalObjectNode createDocument(CosmosAsyncContainer cosmosContainer, Map<String, Object> keyValueProps) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); return BridgeInternal.getProperties(cosmosContainer.createItem(docDefinition).block()); } public List<InternalObjectNode> bulkInsert(CosmosAsyncContainer cosmosContainer, List<Map<String, Object>> keyValuePropsList) { ArrayList<InternalObjectNode> result = new ArrayList<InternalObjectNode>(); for(Map<String, Object> keyValueProps: keyValuePropsList) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); result.add(docDefinition); } return bulkInsertBlocking(cosmosContainer, result); } @BeforeMethod(groups = { "query" }) public void beforeMethod() throws Exception { TimeUnit.SECONDS.sleep(10); } @BeforeClass(groups = { "query" }, timeOut = 4 * SETUP_TIMEOUT) public void before_OrderbyDocumentQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); String containerName = "roundTripsContainer-" + UUID.randomUUID(); createdDatabase.createContainer(containerName, "/mypk", ThroughputProperties.createManualThroughput(10100)).block(); roundTripsContainer = createdDatabase.getContainer(containerName); setupRoundTripContainer(); List<Map<String, Object>> keyValuePropsList = new ArrayList<>(); Map<String, Object> props; boolean flag = false; final int initialDocumentsSize = 30; for(int i = 0; i < initialDocumentsSize; i++) { props = new HashMap<>(); props.put("propInt", i); props.put("propStr", String.valueOf(i)); List<Integer> orderByArray = new ArrayList<Integer>(); Map<String, String> orderByObject = new HashMap<>(); for (int k = 0; k < 3; k++) { orderByArray.add(k + i); orderByObject.put("key1", String.valueOf(i)); orderByObject.put("key2", String.valueOf(orderByArray.get(k))); } props.put("propArray", orderByArray); props.put("propObject", orderByObject); switch (i % 8) { case 0: props.put(PROP_MIXED, i); props.put(PROPTYPE, "number"); break; case 1: props.put(PROP_MIXED, String.valueOf(i)); props.put(PROPTYPE, "string"); break; case 2: props.put(PROP_MIXED, orderByArray); props.put(PROPTYPE, "array"); break; case 3: props.put(PROP_MIXED, orderByObject); props.put(PROPTYPE, "object"); break; case 4: props.put(PROP_MIXED, (float)i*3.17); props.put(PROPTYPE, "number"); break; case 5: props.put(PROP_MIXED, null); props.put(PROPTYPE, "null"); break; case 6: flag = !flag; props.put(PROP_MIXED, flag); props.put(PROPTYPE, "boolean"); break; default: break; } keyValuePropsList.add(props); } props = new HashMap<>(); keyValuePropsList.add(props); createdDocuments = bulkInsert(createdCollection, keyValuePropsList); for(int i = 0; i < 10; i++) { Map<String, Object> p = new HashMap<>(); p.put("propScopedPartitionInt", i); InternalObjectNode doc = getDocumentDefinition("duplicatePartitionKeyValue", UUID.randomUUID().toString(), p); createdDocuments.add(createDocument(createdCollection, doc)); } numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) .readPartitionKeyRanges("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), (CosmosQueryRequestOptions) null) .flatMap(p -> Flux.fromIterable(p.getResults())).collectList().single().block().size(); waitIfNeededForReplicasToCatchUp(getClientBuilder()); updateCollectionIndex(); } private void setupRoundTripContainer() { String pk = "pk1"; for (int i = 0; i < 15; i++) { RoundTripDocument doc; if (i < 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 3); } else if (i == 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } roundTripsContainer.createItem(doc).block(); } pk = "pk2"; for (int i = 0; i < 10; i++) { RoundTripDocument doc; if (i < 1) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 3) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 8) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } pk = "pk3"; for (int i = 0; i < 11; i++) { RoundTripDocument doc; if (i < 2) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 5){ doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 7) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContentWithObjectNode() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<ObjectNode> queryObservable = createdCollection.queryItems(query, options, ObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage().map(response -> ImplementationBridgeHelpers .FeedResponseHelper .getFeedResponseAccessor() .convertGenericType( response, objectNode -> new InternalObjectNode(objectNode) )), validator); } private void updateCollectionIndex() { CosmosContainerProperties containerProperties = createdCollection.read().block().getProperties(); IndexingPolicy indexingPolicy = containerProperties.getIndexingPolicy(); List<IncludedPath> includedPaths = indexingPolicy.getIncludedPaths(); IncludedPath includedPath = new IncludedPath("/propMixed/?"); if (!includedPaths.contains(includedPath)) { includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); containerProperties.setIndexingPolicy(indexingPolicy); createdCollection.replace(containerProperties).block(); } } @AfterClass(groups = { "query" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private void assertInvalidContinuationToken(String query, int[] pageSize, List<String> expectedIds) { String requestContinuation = null; do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(orderByContinuationToken.toString(),1).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertError(CosmosException.class); } while (requestContinuation != null); } private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List<String> expectedIds) { for (int pageSize : pageSizes) { List<InternalObjectNode> receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List<String> actualIds = new ArrayList<String>(); for (InternalObjectNode document : receivedDocuments) { actualIds.add(document.getResourceId()); } assertThat(actualIds).containsExactlyElementsOf(expectedIds); } } private List<InternalObjectNode> queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List<String> continuationTokens = new ArrayList<String>(); List<InternalObjectNode> receivedDocuments = new ArrayList<InternalObjectNode>(); do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(requestContinuation, pageSize).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> firstPage = (FeedResponse<InternalObjectNode>) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); return receivedDocuments; } private static InternalObjectNode getDocumentDefinition(String partitionKey, String id, Map<String, Object> keyValuePair) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); for(String key: keyValuePair.keySet()) { Object val = keyValuePair.get(key); sb.append(" "); sb.append("\"").append(key).append("\"").append(" :" ); if (val == null) { sb.append("null"); } else { sb.append(toJson(val)); } sb.append(",\n"); } sb.append(String.format(" \"id\": \"%s\",\n", id)); sb.append(String.format(" \"mypk\": \"%s\"\n", partitionKey)); sb.append("}"); return new InternalObjectNode(sb.toString()); } private static InternalObjectNode getDocumentDefinition(Map<String, Object> keyValuePair) { String uuid = UUID.randomUUID().toString(); return getDocumentDefinition(uuid, uuid, keyValuePair); } private static String toJson(Object object){ try { return Utils.getSimpleObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } static class RoundTripDocument { @JsonProperty("id") String id; @JsonProperty("mypk") String pk; @JsonProperty("type") String type; @JsonProperty("v") int v; public RoundTripDocument(String id, String pk, String type, int v) { this.id = id; this.pk = pk; this.type = type; this.v = v; } public RoundTripDocument() { } public String getId() { return id; } } }
class OrderbyDocumentQueryTest extends TestSuiteBase { public static final String PROPTYPE = "proptype"; public static final String PROP_MIXED = "propMixed"; private final double minQueryRequestChargePerPartition = 2.0; private CosmosAsyncClient client; private CosmosAsyncContainer createdCollection; private CosmosAsyncContainer roundTripsContainer; private CosmosAsyncDatabase createdDatabase; private List<InternalObjectNode> createdDocuments = new ArrayList<>(); private int numberOfPartitions; @Factory(dataProvider = "clientBuildersWithDirect") public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContent() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @DataProvider(name = "sortOrder") public Object[][] sortOrder() { return new Object[][] { { "ASC" }, {"DESC"} }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderBy(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedResourceIds); } int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValue(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValueAndCustomFactoryMethod(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getImpl(options) .setCustomItemSerializer( new CosmosItemSerializerNoExceptionWrapping() { @Override public <T> Map<String, Object> serialize(T item) { return null; } @Override public <T> T deserialize(Map<String, Object> jsonNodeMap, Class<T> classType) { return (T)(jsonNodeMap.get("_value")); } }); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByInt() throws Exception { String query = "SELECT * FROM r where r.propInt != null ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByString() throws Exception { String query = "SELECT * FROM r where r.propStr != null ORDER BY r.propStr"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<String> validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propStr", d -> d.getString("propStr"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByMixedTypes(String sortOrder) throws Exception { List<PartitionKeyRange> partitionKeyRanges = getPartitionKeyRanges(createdCollection.getId(), BridgeInternal .getContextClient(this.client)); assertThat(partitionKeyRanges.size()).isGreaterThan(1); String query = "SELECT * FROM r ORDER BY r.propMixed "; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> sourceIds = createdDocuments.stream() .map(Resource::getId) .collect(Collectors.toList()); int pageSize = 20; CosmosPagedFlux<InternalObjectNode> queryFlux = createdCollection .queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryFlux.byPage(pageSize).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); List<InternalObjectNode> results = new ArrayList<>(); subscriber.values().forEach(feedResponse -> results.addAll(feedResponse.getResults())); assertThat(results.size()).isEqualTo(createdDocuments.size()); List<String> resultIds = results.stream().map(Resource::getId).collect(Collectors.toList()); assertThat(resultIds).containsExactlyInAnyOrderElementsOf(sourceIds); final List<String> typeList = Arrays.asList("undefined", "null", "boolean", "number", "string", "array", "object"); List<String> observedTypes = new ArrayList<>(); results.forEach(item -> { String propType = "undefined"; if (item.has(PROPTYPE)) { propType = item.getString(PROPTYPE); } if (!observedTypes.contains(propType)) { observedTypes.add(propType); } else { boolean equals = observedTypes.get(observedTypes.size() - 1).equals(propType); assertThat(equals).isTrue().as("Items of same type should be contiguous"); } }); assertThat(observedTypes).containsExactlyElementsOf(typeList); for (String type : typeList) { List<InternalObjectNode> items = results.stream().filter(r -> { if ("undefined".equals(type)) { return !r.has(PROPTYPE); } return type.equals(r.getString(PROPTYPE)); }).collect(Collectors.toList()); if ("boolean".equals(type)) { List<Boolean> sourceList = items.stream().map(n -> n.getBoolean(PROP_MIXED)).collect(Collectors.toList()); List<Boolean> toBeSortedList = new ArrayList<>(sourceList); toBeSortedList.sort(Comparator.comparing(Boolean::booleanValue)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } if ("number".equals(type)) { List<Number> numberList = items.stream().map(n -> (Number) n.get(PROP_MIXED)).collect(Collectors.toList()); List<Number> toBeSortedList = new ArrayList<>(numberList); Collections.copy(toBeSortedList, numberList); toBeSortedList.sort(Comparator.comparingDouble(Number::doubleValue)); assertThat(toBeSortedList).containsExactlyElementsOf(numberList); } if ("string".equals(type)) { List<String> sourceList = items.stream().map(n -> n.getString(PROP_MIXED)).collect(Collectors.toList()); List<String> toBeSortedList = new ArrayList<>(sourceList); Collections.copy(toBeSortedList, sourceList); toBeSortedList.sort(Comparator.comparing(String::valueOf)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } } } private List<PartitionKeyRange> getPartitionKeyRanges( String containerId, AsyncDocumentClient asyncDocumentClient) { List<PartitionKeyRange> partitionKeyRanges = new ArrayList<>(); List<FeedResponse<PartitionKeyRange>> partitionFeedResponseList = asyncDocumentClient .readPartitionKeyRanges("/dbs/" + createdDatabase.getId() + "/colls/" + containerId, new CosmosQueryRequestOptions()) .collectList().block(); partitionFeedResponseList.forEach(f -> partitionKeyRanges.addAll(f.getResults())); return partitionKeyRanges; } @DataProvider(name = "topValue") public Object[][] topValueParameter() { return new Object[][] { { 0 }, { 1 }, { 5 }, { createdDocuments.size() - 1 }, { createdDocuments.size() }, { createdDocuments.size() + 1 }, { 2 * createdDocuments.size() } }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "topValue") public void queryOrderWithTop(int topValue) throws Exception { String query = String.format("SELECT TOP %d * FROM r where r.propInt != null ORDER BY r.propInt", topValue); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator) .stream().limit(topValue).collect(Collectors.toList()); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * (topValue > 0 ? minQueryRequestChargePerPartition : 1)) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } private <T> List<String> sortDocumentsAndCollectResourceIds(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(Resource::getResourceId).collect(Collectors.toList()); } @SuppressWarnings("unchecked") private <T> List<T> sortDocumentsAndCollectValues(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(d -> (T)d.getMap().get(propName)) .collect(Collectors.toList()); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.propScopedPartitionInt ASC"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey("duplicatePartitionKeyValue")); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); int preferredPageSize = 3; TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryObservable.byPage(preferredPageSize).take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> page = (FeedResponse<InternalObjectNode>) subscriber.getEvents().get(0).get(0); assertThat(page.getResults()).hasSize(3); assertThat(page.getContinuationToken()).isNotEmpty(); queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<InternalObjectNode> expectedDocs = createdDocuments.stream() .filter(d -> (StringUtils.equals("duplicatePartitionKeyValue", d.getString("mypk")))) .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList()); int expectedPageSize = (expectedDocs.size() + preferredPageSize - 1) / preferredPageSize; assertThat(expectedDocs).hasSize(10 - 3); FeedResponseListValidator<InternalObjectNode> validator = null; validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(page.getContinuationToken(), preferredPageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void orderByContinuationTokenRoundTrip() throws Exception { { OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); String serialized = orderByContinuationToken.toString(); ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse(serialized, outOrderByContinuationToken)).isTrue(); OrderByContinuationToken deserialized = outOrderByContinuationToken.v; CompositeContinuationToken compositeContinuationToken = deserialized.getCompositeContinuationToken(); String token = compositeContinuationToken.getToken(); Range<String> range = compositeContinuationToken.getRange(); assertThat(token).isEqualTo("asdf"); assertThat(range.getMin()).isEqualTo("A"); assertThat(range.getMax()).isEqualTo("D"); assertThat(range.isMinInclusive()).isEqualTo(false); assertThat(range.isMaxInclusive()).isEqualTo(true); QueryItem[] orderByItems = deserialized.getOrderByItems(); assertThat(orderByItems).isNotNull(); assertThat(orderByItems.length).isEqualTo(1); assertThat(orderByItems[0].getItem()).isEqualTo(42); String rid = deserialized.getRid(); assertThat(rid).isEqualTo("rid"); boolean inclusive = deserialized.getInclusive(); assertThat(inclusive).isEqualTo(false); } { ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse("{\"property\" : \"Not a valid Order By Token\"}", outOrderByContinuationToken)).isFalse(); } } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); Comparator<Integer> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<Integer> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100}, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<String> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> validatorComparator; if(sortOrder.equals("ASC")) { validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); }else{ validatorComparator = Comparator.nullsFirst(Comparator.<String>reverseOrder()); } List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.assertInvalidContinuationToken(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByArray(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propArray != null ORDER BY r.propArray %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByObject(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propObject != null ORDER BY r.propObject %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } public InternalObjectNode createDocument(CosmosAsyncContainer cosmosContainer, Map<String, Object> keyValueProps) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); return BridgeInternal.getProperties(cosmosContainer.createItem(docDefinition).block()); } public List<InternalObjectNode> bulkInsert(CosmosAsyncContainer cosmosContainer, List<Map<String, Object>> keyValuePropsList) { ArrayList<InternalObjectNode> result = new ArrayList<InternalObjectNode>(); for(Map<String, Object> keyValueProps: keyValuePropsList) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); result.add(docDefinition); } return bulkInsertBlocking(cosmosContainer, result); } @BeforeMethod(groups = { "query" }) public void beforeMethod() throws Exception { TimeUnit.SECONDS.sleep(10); } @BeforeClass(groups = { "query" }, timeOut = 4 * SETUP_TIMEOUT) public void before_OrderbyDocumentQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); String containerName = "roundTripsContainer-" + UUID.randomUUID(); createdDatabase.createContainer(containerName, "/mypk", ThroughputProperties.createManualThroughput(10100)).block(); roundTripsContainer = createdDatabase.getContainer(containerName); setupRoundTripContainer(); List<Map<String, Object>> keyValuePropsList = new ArrayList<>(); Map<String, Object> props; boolean flag = false; final int initialDocumentsSize = 30; for(int i = 0; i < initialDocumentsSize; i++) { props = new HashMap<>(); props.put("propInt", i); props.put("propStr", String.valueOf(i)); List<Integer> orderByArray = new ArrayList<Integer>(); Map<String, String> orderByObject = new HashMap<>(); for (int k = 0; k < 3; k++) { orderByArray.add(k + i); orderByObject.put("key1", String.valueOf(i)); orderByObject.put("key2", String.valueOf(orderByArray.get(k))); } props.put("propArray", orderByArray); props.put("propObject", orderByObject); switch (i % 8) { case 0: props.put(PROP_MIXED, i); props.put(PROPTYPE, "number"); break; case 1: props.put(PROP_MIXED, String.valueOf(i)); props.put(PROPTYPE, "string"); break; case 2: props.put(PROP_MIXED, orderByArray); props.put(PROPTYPE, "array"); break; case 3: props.put(PROP_MIXED, orderByObject); props.put(PROPTYPE, "object"); break; case 4: props.put(PROP_MIXED, (float)i*3.17); props.put(PROPTYPE, "number"); break; case 5: props.put(PROP_MIXED, null); props.put(PROPTYPE, "null"); break; case 6: flag = !flag; props.put(PROP_MIXED, flag); props.put(PROPTYPE, "boolean"); break; default: break; } keyValuePropsList.add(props); } props = new HashMap<>(); keyValuePropsList.add(props); createdDocuments = bulkInsert(createdCollection, keyValuePropsList); for(int i = 0; i < 10; i++) { Map<String, Object> p = new HashMap<>(); p.put("propScopedPartitionInt", i); InternalObjectNode doc = getDocumentDefinition("duplicatePartitionKeyValue", UUID.randomUUID().toString(), p); createdDocuments.add(createDocument(createdCollection, doc)); } numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) .readPartitionKeyRanges("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), (CosmosQueryRequestOptions) null) .flatMap(p -> Flux.fromIterable(p.getResults())).collectList().single().block().size(); waitIfNeededForReplicasToCatchUp(getClientBuilder()); updateCollectionIndex(); } private void setupRoundTripContainer() { String pk = "pk1"; for (int i = 0; i < 15; i++) { RoundTripDocument doc; if (i < 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 3); } else if (i == 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } roundTripsContainer.createItem(doc).block(); } pk = "pk2"; for (int i = 0; i < 10; i++) { RoundTripDocument doc; if (i < 1) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 3) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 8) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } pk = "pk3"; for (int i = 0; i < 11; i++) { RoundTripDocument doc; if (i < 2) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 5){ doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 7) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContentWithObjectNode() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<ObjectNode> queryObservable = createdCollection.queryItems(query, options, ObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage().map(response -> ImplementationBridgeHelpers .FeedResponseHelper .getFeedResponseAccessor() .convertGenericType( response, objectNode -> new InternalObjectNode(objectNode) )), validator); } private void updateCollectionIndex() { CosmosContainerProperties containerProperties = createdCollection.read().block().getProperties(); IndexingPolicy indexingPolicy = containerProperties.getIndexingPolicy(); List<IncludedPath> includedPaths = indexingPolicy.getIncludedPaths(); IncludedPath includedPath = new IncludedPath("/propMixed/?"); if (!includedPaths.contains(includedPath)) { includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); containerProperties.setIndexingPolicy(indexingPolicy); createdCollection.replace(containerProperties).block(); } } @AfterClass(groups = { "query" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private void assertInvalidContinuationToken(String query, int[] pageSize, List<String> expectedIds) { String requestContinuation = null; do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(orderByContinuationToken.toString(),1).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertError(CosmosException.class); } while (requestContinuation != null); } private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List<String> expectedIds) { for (int pageSize : pageSizes) { List<InternalObjectNode> receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List<String> actualIds = new ArrayList<String>(); for (InternalObjectNode document : receivedDocuments) { actualIds.add(document.getResourceId()); } assertThat(actualIds).containsExactlyElementsOf(expectedIds); } } private List<InternalObjectNode> queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List<String> continuationTokens = new ArrayList<String>(); List<InternalObjectNode> receivedDocuments = new ArrayList<InternalObjectNode>(); do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(requestContinuation, pageSize).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> firstPage = (FeedResponse<InternalObjectNode>) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); return receivedDocuments; } private static InternalObjectNode getDocumentDefinition(String partitionKey, String id, Map<String, Object> keyValuePair) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); for(String key: keyValuePair.keySet()) { Object val = keyValuePair.get(key); sb.append(" "); sb.append("\"").append(key).append("\"").append(" :" ); if (val == null) { sb.append("null"); } else { sb.append(toJson(val)); } sb.append(",\n"); } sb.append(String.format(" \"id\": \"%s\",\n", id)); sb.append(String.format(" \"mypk\": \"%s\"\n", partitionKey)); sb.append("}"); return new InternalObjectNode(sb.toString()); } private static InternalObjectNode getDocumentDefinition(Map<String, Object> keyValuePair) { String uuid = UUID.randomUUID().toString(); return getDocumentDefinition(uuid, uuid, keyValuePair); } private static String toJson(Object object){ try { return Utils.getSimpleObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } static class RoundTripDocument { @JsonProperty("id") String id; @JsonProperty("mypk") String pk; @JsonProperty("type") String type; @JsonProperty("v") int v; public RoundTripDocument(String id, String pk, String type, int v) { this.id = id; this.pk = pk; this.type = type; this.v = v; } public RoundTripDocument() { } public String getId() { return id; } } }
True it is possible without the change that the test might pass. It should be max 4 requests for this test. One for each partition and one for each prefetch per partition. To make it more robust, I do it 100 times and I'm checking the outputDocuments to be max 10 (2 pages) and the requests captured in the diagnostics to be max 4. With these changes, the test will be unlikely to pass without the change.
public void queryOrderByRoundTrips() { String query = "SELECT c.v FROM c where c.type='testing' order by c.v asc"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 5; CosmosPagedFlux<RoundTripDocument> queryObservable = roundTripsContainer.queryItems(query, options, RoundTripDocument.class); FeedResponse<RoundTripDocument> feedResponse = queryObservable.byPage(pageSize).take(1).blockFirst(); assertThat(feedResponse.getResults().size()).isEqualTo(5); for (RoundTripDocument roundTripDocument : feedResponse.getResults()) { assertThat(roundTripDocument.v).isEqualTo(3); } FeedResponseDiagnostics feedResponseDiagnostics = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor().getFeedResponseDiagnostics(feedResponse.getCosmosDiagnostics()); assertThat(feedResponseDiagnostics.getClientSideRequestStatistics().size()).isEqualTo(3); }
FeedResponse<RoundTripDocument> feedResponse = queryObservable.byPage(pageSize).take(1).blockFirst();
public void queryOrderByRoundTrips() { String query = "SELECT c.v FROM c where c.type='testing' order by c.v asc"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 5; for (int i = 0; i < 100; i++) { CosmosPagedFlux<RoundTripDocument> queryObservable = roundTripsContainer.queryItems(query, options, RoundTripDocument.class); FeedResponse<RoundTripDocument> feedResponse = queryObservable.byPage(pageSize).take(1).blockFirst(); assertThat(feedResponse.getResults().size()).isEqualTo(5); for (RoundTripDocument roundTripDocument : feedResponse.getResults()) { assertThat(roundTripDocument.v).isEqualTo(3); } Map<String, QueryMetrics> queryMetricsMap = ModelBridgeInternal.queryMetricsMap(feedResponse); List<QueryMetrics> queryMetrics = new ArrayList<>(queryMetricsMap.values()); for (QueryMetrics queryMetric : queryMetrics) { assertThat(queryMetric.getOutputDocumentCount()).isLessThanOrEqualTo(10); } FeedResponseDiagnostics feedResponseDiagnostics = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor().getFeedResponseDiagnostics(feedResponse.getCosmosDiagnostics()); assertThat(feedResponseDiagnostics.getClientSideRequestStatistics().size()).isLessThanOrEqualTo(4); } }
class OrderbyDocumentQueryTest extends TestSuiteBase { public static final String PROPTYPE = "proptype"; public static final String PROP_MIXED = "propMixed"; private final double minQueryRequestChargePerPartition = 2.0; private CosmosAsyncClient client; private CosmosAsyncContainer createdCollection; private CosmosAsyncContainer roundTripsContainer; private CosmosAsyncDatabase createdDatabase; private List<InternalObjectNode> createdDocuments = new ArrayList<>(); private int numberOfPartitions; @Factory(dataProvider = "clientBuildersWithDirect") public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContent() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @DataProvider(name = "sortOrder") public Object[][] sortOrder() { return new Object[][] { { "ASC" }, {"DESC"} }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderBy(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedResourceIds); } int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValue(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValueAndCustomFactoryMethod(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getImpl(options) .setCustomItemSerializer( new CosmosItemSerializerNoExceptionWrapping() { @Override public <T> Map<String, Object> serialize(T item) { return null; } @Override public <T> T deserialize(Map<String, Object> jsonNodeMap, Class<T> classType) { return (T)(jsonNodeMap.get("_value")); } }); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByInt() throws Exception { String query = "SELECT * FROM r where r.propInt != null ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByString() throws Exception { String query = "SELECT * FROM r where r.propStr != null ORDER BY r.propStr"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<String> validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propStr", d -> d.getString("propStr"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByMixedTypes(String sortOrder) throws Exception { List<PartitionKeyRange> partitionKeyRanges = getPartitionKeyRanges(createdCollection.getId(), BridgeInternal .getContextClient(this.client)); assertThat(partitionKeyRanges.size()).isGreaterThan(1); String query = "SELECT * FROM r ORDER BY r.propMixed "; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> sourceIds = createdDocuments.stream() .map(Resource::getId) .collect(Collectors.toList()); int pageSize = 20; CosmosPagedFlux<InternalObjectNode> queryFlux = createdCollection .queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryFlux.byPage(pageSize).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); List<InternalObjectNode> results = new ArrayList<>(); subscriber.values().forEach(feedResponse -> results.addAll(feedResponse.getResults())); assertThat(results.size()).isEqualTo(createdDocuments.size()); List<String> resultIds = results.stream().map(Resource::getId).collect(Collectors.toList()); assertThat(resultIds).containsExactlyInAnyOrderElementsOf(sourceIds); final List<String> typeList = Arrays.asList("undefined", "null", "boolean", "number", "string", "array", "object"); List<String> observedTypes = new ArrayList<>(); results.forEach(item -> { String propType = "undefined"; if (item.has(PROPTYPE)) { propType = item.getString(PROPTYPE); } if (!observedTypes.contains(propType)) { observedTypes.add(propType); } else { boolean equals = observedTypes.get(observedTypes.size() - 1).equals(propType); assertThat(equals).isTrue().as("Items of same type should be contiguous"); } }); assertThat(observedTypes).containsExactlyElementsOf(typeList); for (String type : typeList) { List<InternalObjectNode> items = results.stream().filter(r -> { if ("undefined".equals(type)) { return !r.has(PROPTYPE); } return type.equals(r.getString(PROPTYPE)); }).collect(Collectors.toList()); if ("boolean".equals(type)) { List<Boolean> sourceList = items.stream().map(n -> n.getBoolean(PROP_MIXED)).collect(Collectors.toList()); List<Boolean> toBeSortedList = new ArrayList<>(sourceList); toBeSortedList.sort(Comparator.comparing(Boolean::booleanValue)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } if ("number".equals(type)) { List<Number> numberList = items.stream().map(n -> (Number) n.get(PROP_MIXED)).collect(Collectors.toList()); List<Number> toBeSortedList = new ArrayList<>(numberList); Collections.copy(toBeSortedList, numberList); toBeSortedList.sort(Comparator.comparingDouble(Number::doubleValue)); assertThat(toBeSortedList).containsExactlyElementsOf(numberList); } if ("string".equals(type)) { List<String> sourceList = items.stream().map(n -> n.getString(PROP_MIXED)).collect(Collectors.toList()); List<String> toBeSortedList = new ArrayList<>(sourceList); Collections.copy(toBeSortedList, sourceList); toBeSortedList.sort(Comparator.comparing(String::valueOf)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } } } private List<PartitionKeyRange> getPartitionKeyRanges( String containerId, AsyncDocumentClient asyncDocumentClient) { List<PartitionKeyRange> partitionKeyRanges = new ArrayList<>(); List<FeedResponse<PartitionKeyRange>> partitionFeedResponseList = asyncDocumentClient .readPartitionKeyRanges("/dbs/" + createdDatabase.getId() + "/colls/" + containerId, new CosmosQueryRequestOptions()) .collectList().block(); partitionFeedResponseList.forEach(f -> partitionKeyRanges.addAll(f.getResults())); return partitionKeyRanges; } @DataProvider(name = "topValue") public Object[][] topValueParameter() { return new Object[][] { { 0 }, { 1 }, { 5 }, { createdDocuments.size() - 1 }, { createdDocuments.size() }, { createdDocuments.size() + 1 }, { 2 * createdDocuments.size() } }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "topValue") public void queryOrderWithTop(int topValue) throws Exception { String query = String.format("SELECT TOP %d * FROM r where r.propInt != null ORDER BY r.propInt", topValue); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator) .stream().limit(topValue).collect(Collectors.toList()); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * (topValue > 0 ? minQueryRequestChargePerPartition : 1)) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } private <T> List<String> sortDocumentsAndCollectResourceIds(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(Resource::getResourceId).collect(Collectors.toList()); } @SuppressWarnings("unchecked") private <T> List<T> sortDocumentsAndCollectValues(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(d -> (T)d.getMap().get(propName)) .collect(Collectors.toList()); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.propScopedPartitionInt ASC"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey("duplicatePartitionKeyValue")); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); int preferredPageSize = 3; TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryObservable.byPage(preferredPageSize).take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> page = (FeedResponse<InternalObjectNode>) subscriber.getEvents().get(0).get(0); assertThat(page.getResults()).hasSize(3); assertThat(page.getContinuationToken()).isNotEmpty(); queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<InternalObjectNode> expectedDocs = createdDocuments.stream() .filter(d -> (StringUtils.equals("duplicatePartitionKeyValue", d.getString("mypk")))) .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList()); int expectedPageSize = (expectedDocs.size() + preferredPageSize - 1) / preferredPageSize; assertThat(expectedDocs).hasSize(10 - 3); FeedResponseListValidator<InternalObjectNode> validator = null; validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(page.getContinuationToken(), preferredPageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void orderByContinuationTokenRoundTrip() throws Exception { { OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); String serialized = orderByContinuationToken.toString(); ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse(serialized, outOrderByContinuationToken)).isTrue(); OrderByContinuationToken deserialized = outOrderByContinuationToken.v; CompositeContinuationToken compositeContinuationToken = deserialized.getCompositeContinuationToken(); String token = compositeContinuationToken.getToken(); Range<String> range = compositeContinuationToken.getRange(); assertThat(token).isEqualTo("asdf"); assertThat(range.getMin()).isEqualTo("A"); assertThat(range.getMax()).isEqualTo("D"); assertThat(range.isMinInclusive()).isEqualTo(false); assertThat(range.isMaxInclusive()).isEqualTo(true); QueryItem[] orderByItems = deserialized.getOrderByItems(); assertThat(orderByItems).isNotNull(); assertThat(orderByItems.length).isEqualTo(1); assertThat(orderByItems[0].getItem()).isEqualTo(42); String rid = deserialized.getRid(); assertThat(rid).isEqualTo("rid"); boolean inclusive = deserialized.getInclusive(); assertThat(inclusive).isEqualTo(false); } { ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse("{\"property\" : \"Not a valid Order By Token\"}", outOrderByContinuationToken)).isFalse(); } } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); Comparator<Integer> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<Integer> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100}, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<String> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> validatorComparator; if(sortOrder.equals("ASC")) { validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); }else{ validatorComparator = Comparator.nullsFirst(Comparator.<String>reverseOrder()); } List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.assertInvalidContinuationToken(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByArray(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propArray != null ORDER BY r.propArray %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByObject(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propObject != null ORDER BY r.propObject %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } public InternalObjectNode createDocument(CosmosAsyncContainer cosmosContainer, Map<String, Object> keyValueProps) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); return BridgeInternal.getProperties(cosmosContainer.createItem(docDefinition).block()); } public List<InternalObjectNode> bulkInsert(CosmosAsyncContainer cosmosContainer, List<Map<String, Object>> keyValuePropsList) { ArrayList<InternalObjectNode> result = new ArrayList<InternalObjectNode>(); for(Map<String, Object> keyValueProps: keyValuePropsList) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); result.add(docDefinition); } return bulkInsertBlocking(cosmosContainer, result); } @BeforeMethod(groups = { "query" }) public void beforeMethod() throws Exception { TimeUnit.SECONDS.sleep(10); } @BeforeClass(groups = { "query" }, timeOut = 4 * SETUP_TIMEOUT) public void before_OrderbyDocumentQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); String containerName = "roundTripsContainer-" + UUID.randomUUID(); createdDatabase.createContainer(containerName, "/mypk", ThroughputProperties.createManualThroughput(10100)).block(); roundTripsContainer = createdDatabase.getContainer(containerName); setupRoundTripContainer(); List<Map<String, Object>> keyValuePropsList = new ArrayList<>(); Map<String, Object> props; boolean flag = false; final int initialDocumentsSize = 30; for(int i = 0; i < initialDocumentsSize; i++) { props = new HashMap<>(); props.put("propInt", i); props.put("propStr", String.valueOf(i)); List<Integer> orderByArray = new ArrayList<Integer>(); Map<String, String> orderByObject = new HashMap<>(); for (int k = 0; k < 3; k++) { orderByArray.add(k + i); orderByObject.put("key1", String.valueOf(i)); orderByObject.put("key2", String.valueOf(orderByArray.get(k))); } props.put("propArray", orderByArray); props.put("propObject", orderByObject); switch (i % 8) { case 0: props.put(PROP_MIXED, i); props.put(PROPTYPE, "number"); break; case 1: props.put(PROP_MIXED, String.valueOf(i)); props.put(PROPTYPE, "string"); break; case 2: props.put(PROP_MIXED, orderByArray); props.put(PROPTYPE, "array"); break; case 3: props.put(PROP_MIXED, orderByObject); props.put(PROPTYPE, "object"); break; case 4: props.put(PROP_MIXED, (float)i*3.17); props.put(PROPTYPE, "number"); break; case 5: props.put(PROP_MIXED, null); props.put(PROPTYPE, "null"); break; case 6: flag = !flag; props.put(PROP_MIXED, flag); props.put(PROPTYPE, "boolean"); break; default: break; } keyValuePropsList.add(props); } props = new HashMap<>(); keyValuePropsList.add(props); createdDocuments = bulkInsert(createdCollection, keyValuePropsList); for(int i = 0; i < 10; i++) { Map<String, Object> p = new HashMap<>(); p.put("propScopedPartitionInt", i); InternalObjectNode doc = getDocumentDefinition("duplicatePartitionKeyValue", UUID.randomUUID().toString(), p); createdDocuments.add(createDocument(createdCollection, doc)); } numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) .readPartitionKeyRanges("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), (CosmosQueryRequestOptions) null) .flatMap(p -> Flux.fromIterable(p.getResults())).collectList().single().block().size(); waitIfNeededForReplicasToCatchUp(getClientBuilder()); updateCollectionIndex(); } private void setupRoundTripContainer() { String pk = "pk1"; for (int i = 0; i < 15; i++) { RoundTripDocument doc; if (i < 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 3); } else if (i == 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } roundTripsContainer.createItem(doc).block(); } pk = "pk2"; for (int i = 0; i < 10; i++) { RoundTripDocument doc; if (i < 1) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 3) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 8) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } pk = "pk3"; for (int i = 0; i < 11; i++) { RoundTripDocument doc; if (i < 2) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 5){ doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 7) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContentWithObjectNode() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<ObjectNode> queryObservable = createdCollection.queryItems(query, options, ObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage().map(response -> ImplementationBridgeHelpers .FeedResponseHelper .getFeedResponseAccessor() .convertGenericType( response, objectNode -> new InternalObjectNode(objectNode) )), validator); } private void updateCollectionIndex() { CosmosContainerProperties containerProperties = createdCollection.read().block().getProperties(); IndexingPolicy indexingPolicy = containerProperties.getIndexingPolicy(); List<IncludedPath> includedPaths = indexingPolicy.getIncludedPaths(); IncludedPath includedPath = new IncludedPath("/propMixed/?"); if (!includedPaths.contains(includedPath)) { includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); containerProperties.setIndexingPolicy(indexingPolicy); createdCollection.replace(containerProperties).block(); } } @AfterClass(groups = { "query" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private void assertInvalidContinuationToken(String query, int[] pageSize, List<String> expectedIds) { String requestContinuation = null; do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(orderByContinuationToken.toString(),1).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertError(CosmosException.class); } while (requestContinuation != null); } private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List<String> expectedIds) { for (int pageSize : pageSizes) { List<InternalObjectNode> receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List<String> actualIds = new ArrayList<String>(); for (InternalObjectNode document : receivedDocuments) { actualIds.add(document.getResourceId()); } assertThat(actualIds).containsExactlyElementsOf(expectedIds); } } private List<InternalObjectNode> queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List<String> continuationTokens = new ArrayList<String>(); List<InternalObjectNode> receivedDocuments = new ArrayList<InternalObjectNode>(); do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(requestContinuation, pageSize).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> firstPage = (FeedResponse<InternalObjectNode>) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); return receivedDocuments; } private static InternalObjectNode getDocumentDefinition(String partitionKey, String id, Map<String, Object> keyValuePair) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); for(String key: keyValuePair.keySet()) { Object val = keyValuePair.get(key); sb.append(" "); sb.append("\"").append(key).append("\"").append(" :" ); if (val == null) { sb.append("null"); } else { sb.append(toJson(val)); } sb.append(",\n"); } sb.append(String.format(" \"id\": \"%s\",\n", id)); sb.append(String.format(" \"mypk\": \"%s\"\n", partitionKey)); sb.append("}"); return new InternalObjectNode(sb.toString()); } private static InternalObjectNode getDocumentDefinition(Map<String, Object> keyValuePair) { String uuid = UUID.randomUUID().toString(); return getDocumentDefinition(uuid, uuid, keyValuePair); } private static String toJson(Object object){ try { return Utils.getSimpleObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } static class RoundTripDocument { @JsonProperty("id") String id; @JsonProperty("mypk") String pk; @JsonProperty("type") String type; @JsonProperty("v") int v; public RoundTripDocument(String id, String pk, String type, int v) { this.id = id; this.pk = pk; this.type = type; this.v = v; } public RoundTripDocument() { } public String getId() { return id; } } }
class OrderbyDocumentQueryTest extends TestSuiteBase { public static final String PROPTYPE = "proptype"; public static final String PROP_MIXED = "propMixed"; private final double minQueryRequestChargePerPartition = 2.0; private CosmosAsyncClient client; private CosmosAsyncContainer createdCollection; private CosmosAsyncContainer roundTripsContainer; private CosmosAsyncDatabase createdDatabase; private List<InternalObjectNode> createdDocuments = new ArrayList<>(); private int numberOfPartitions; @Factory(dataProvider = "clientBuildersWithDirect") public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContent() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @DataProvider(name = "sortOrder") public Object[][] sortOrder() { return new Object[][] { { "ASC" }, {"DESC"} }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderBy(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedResourceIds); } int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValue(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByWithValueAndCustomFactoryMethod(String sortOrder) throws Exception { String query = String.format("SELECT value r.propInt FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getImpl(options) .setCustomItemSerializer( new CosmosItemSerializerNoExceptionWrapping() { @Override public <T> Map<String, Object> serialize(T item) { return null; } @Override public <T> T deserialize(Map<String, Object> jsonNodeMap, Class<T> classType) { return (T)(jsonNodeMap.get("_value")); } }); int pageSize = 3; CosmosPagedFlux<Integer> queryObservable = createdCollection.queryItems(query, options, Integer.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<Integer> expectedValues = sortDocumentsAndCollectValues("propInt", d -> d.getInt("propInt"), validatorComparator); if ("DESC".equals(sortOrder)) { Collections.reverse(expectedValues); } int expectedPageSize = expectedNumberOfPages(expectedValues.size(), pageSize); FeedResponseListValidator<Integer> validator = new FeedResponseListValidator.Builder<Integer>() .containsExactlyValues(expectedValues) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<Integer>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByInt() throws Exception { String query = "SELECT * FROM r where r.propInt != null ORDER BY r.propInt"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryOrderByString() throws Exception { String query = "SELECT * FROM r where r.propStr != null ORDER BY r.propStr"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<String> validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propStr", d -> d.getString("propStr"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByMixedTypes(String sortOrder) throws Exception { List<PartitionKeyRange> partitionKeyRanges = getPartitionKeyRanges(createdCollection.getId(), BridgeInternal .getContextClient(this.client)); assertThat(partitionKeyRanges.size()).isGreaterThan(1); String query = "SELECT * FROM r ORDER BY r.propMixed "; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); List<String> sourceIds = createdDocuments.stream() .map(Resource::getId) .collect(Collectors.toList()); int pageSize = 20; CosmosPagedFlux<InternalObjectNode> queryFlux = createdCollection .queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryFlux.byPage(pageSize).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); List<InternalObjectNode> results = new ArrayList<>(); subscriber.values().forEach(feedResponse -> results.addAll(feedResponse.getResults())); assertThat(results.size()).isEqualTo(createdDocuments.size()); List<String> resultIds = results.stream().map(Resource::getId).collect(Collectors.toList()); assertThat(resultIds).containsExactlyInAnyOrderElementsOf(sourceIds); final List<String> typeList = Arrays.asList("undefined", "null", "boolean", "number", "string", "array", "object"); List<String> observedTypes = new ArrayList<>(); results.forEach(item -> { String propType = "undefined"; if (item.has(PROPTYPE)) { propType = item.getString(PROPTYPE); } if (!observedTypes.contains(propType)) { observedTypes.add(propType); } else { boolean equals = observedTypes.get(observedTypes.size() - 1).equals(propType); assertThat(equals).isTrue().as("Items of same type should be contiguous"); } }); assertThat(observedTypes).containsExactlyElementsOf(typeList); for (String type : typeList) { List<InternalObjectNode> items = results.stream().filter(r -> { if ("undefined".equals(type)) { return !r.has(PROPTYPE); } return type.equals(r.getString(PROPTYPE)); }).collect(Collectors.toList()); if ("boolean".equals(type)) { List<Boolean> sourceList = items.stream().map(n -> n.getBoolean(PROP_MIXED)).collect(Collectors.toList()); List<Boolean> toBeSortedList = new ArrayList<>(sourceList); toBeSortedList.sort(Comparator.comparing(Boolean::booleanValue)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } if ("number".equals(type)) { List<Number> numberList = items.stream().map(n -> (Number) n.get(PROP_MIXED)).collect(Collectors.toList()); List<Number> toBeSortedList = new ArrayList<>(numberList); Collections.copy(toBeSortedList, numberList); toBeSortedList.sort(Comparator.comparingDouble(Number::doubleValue)); assertThat(toBeSortedList).containsExactlyElementsOf(numberList); } if ("string".equals(type)) { List<String> sourceList = items.stream().map(n -> n.getString(PROP_MIXED)).collect(Collectors.toList()); List<String> toBeSortedList = new ArrayList<>(sourceList); Collections.copy(toBeSortedList, sourceList); toBeSortedList.sort(Comparator.comparing(String::valueOf)); assertThat(toBeSortedList).containsExactlyElementsOf(sourceList); } } } private List<PartitionKeyRange> getPartitionKeyRanges( String containerId, AsyncDocumentClient asyncDocumentClient) { List<PartitionKeyRange> partitionKeyRanges = new ArrayList<>(); List<FeedResponse<PartitionKeyRange>> partitionFeedResponseList = asyncDocumentClient .readPartitionKeyRanges("/dbs/" + createdDatabase.getId() + "/colls/" + containerId, new CosmosQueryRequestOptions()) .collectList().block(); partitionFeedResponseList.forEach(f -> partitionKeyRanges.addAll(f.getResults())); return partitionKeyRanges; } @DataProvider(name = "topValue") public Object[][] topValueParameter() { return new Object[][] { { 0 }, { 1 }, { 5 }, { createdDocuments.size() - 1 }, { createdDocuments.size() }, { createdDocuments.size() + 1 }, { 2 * createdDocuments.size() } }; } @Test(groups = { "query" }, timeOut = TIMEOUT, dataProvider = "topValue") public void queryOrderWithTop(int topValue) throws Exception { String query = String.format("SELECT TOP %d * FROM r where r.propInt != null ORDER BY r.propInt", topValue); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); int pageSize = 3; CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); Comparator<Integer> validatorComparator = Comparator.nullsFirst(Comparator.<Integer>naturalOrder()); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator) .stream().limit(topValue).collect(Collectors.toList()); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * (topValue > 0 ? minQueryRequestChargePerPartition : 1)) .build(); validateQuerySuccess(queryObservable.byPage(pageSize), validator); } private <T> List<String> sortDocumentsAndCollectResourceIds(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(Resource::getResourceId).collect(Collectors.toList()); } @SuppressWarnings("unchecked") private <T> List<T> sortDocumentsAndCollectValues(String propName, Function<InternalObjectNode, T> extractProp, Comparator<T> comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(d -> (T)d.getMap().get(propName)) .collect(Collectors.toList()); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.propScopedPartitionInt ASC"; CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey("duplicatePartitionKeyValue")); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); int preferredPageSize = 3; TestSubscriber<FeedResponse<InternalObjectNode>> subscriber = new TestSubscriber<>(); queryObservable.byPage(preferredPageSize).take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> page = (FeedResponse<InternalObjectNode>) subscriber.getEvents().get(0).get(0); assertThat(page.getResults()).hasSize(3); assertThat(page.getContinuationToken()).isNotEmpty(); queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); List<InternalObjectNode> expectedDocs = createdDocuments.stream() .filter(d -> (StringUtils.equals("duplicatePartitionKeyValue", d.getString("mypk")))) .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList()); int expectedPageSize = (expectedDocs.size() + preferredPageSize - 1) / preferredPageSize; assertThat(expectedDocs).hasSize(10 - 3); FeedResponseListValidator<InternalObjectNode> validator = null; validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(page.getContinuationToken(), preferredPageSize), validator); } @Test(groups = { "query" }, timeOut = TIMEOUT) public void orderByContinuationTokenRoundTrip() throws Exception { { OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); String serialized = orderByContinuationToken.toString(); ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse(serialized, outOrderByContinuationToken)).isTrue(); OrderByContinuationToken deserialized = outOrderByContinuationToken.v; CompositeContinuationToken compositeContinuationToken = deserialized.getCompositeContinuationToken(); String token = compositeContinuationToken.getToken(); Range<String> range = compositeContinuationToken.getRange(); assertThat(token).isEqualTo("asdf"); assertThat(range.getMin()).isEqualTo("A"); assertThat(range.getMax()).isEqualTo("D"); assertThat(range.isMinInclusive()).isEqualTo(false); assertThat(range.isMaxInclusive()).isEqualTo(true); QueryItem[] orderByItems = deserialized.getOrderByItems(); assertThat(orderByItems).isNotNull(); assertThat(orderByItems.length).isEqualTo(1); assertThat(orderByItems[0].getItem()).isEqualTo(42); String rid = deserialized.getRid(); assertThat(rid).isEqualTo("rid"); boolean inclusive = deserialized.getInclusive(); assertThat(inclusive).isEqualTo(false); } { ValueHolder<OrderByContinuationToken> outOrderByContinuationToken = new ValueHolder<OrderByContinuationToken>(); assertThat(OrderByContinuationToken.tryParse("{\"property\" : \"Not a valid Order By Token\"}", outOrderByContinuationToken)).isFalse(); } } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propInt != null ORDER BY r.propInt %s", sortOrder); Comparator<Integer> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<Integer> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100}, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder(); Comparator<String> validatorComparator = Comparator.nullsFirst(order); List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = { "query" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sortOrder) throws Exception { String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder); Comparator<String> validatorComparator; if(sortOrder.equals("ASC")) { validatorComparator = Comparator.nullsFirst(Comparator.<String>naturalOrder()); }else{ validatorComparator = Comparator.nullsFirst(Comparator.<String>reverseOrder()); } List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator); this.assertInvalidContinuationToken(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByArray(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propArray != null ORDER BY r.propArray %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } @Test(groups = {"query"}, timeOut = TIMEOUT, dataProvider = "sortOrder") public void queryOrderByObject(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r where r.propObject != null ORDER BY r.propObject %s", sortOrder); int pageSize = 3; List<InternalObjectNode> results1 = this.queryWithContinuationTokens(query, pageSize); List<InternalObjectNode> results2 = this.queryWithContinuationTokens(query, this.createdDocuments.size()); assertThat(results1.stream().map(r -> r.getResourceId()).collect(Collectors.toList())) .containsExactlyElementsOf(results2.stream().limit(pageSize).map(r -> r.getResourceId()).collect(Collectors.toList())); } public InternalObjectNode createDocument(CosmosAsyncContainer cosmosContainer, Map<String, Object> keyValueProps) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); return BridgeInternal.getProperties(cosmosContainer.createItem(docDefinition).block()); } public List<InternalObjectNode> bulkInsert(CosmosAsyncContainer cosmosContainer, List<Map<String, Object>> keyValuePropsList) { ArrayList<InternalObjectNode> result = new ArrayList<InternalObjectNode>(); for(Map<String, Object> keyValueProps: keyValuePropsList) { InternalObjectNode docDefinition = getDocumentDefinition(keyValueProps); result.add(docDefinition); } return bulkInsertBlocking(cosmosContainer, result); } @BeforeMethod(groups = { "query" }) public void beforeMethod() throws Exception { TimeUnit.SECONDS.sleep(10); } @BeforeClass(groups = { "query" }, timeOut = 4 * SETUP_TIMEOUT) public void before_OrderbyDocumentQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); String containerName = "roundTripsContainer-" + UUID.randomUUID(); createdDatabase.createContainer(containerName, "/mypk", ThroughputProperties.createManualThroughput(10100)).block(); roundTripsContainer = createdDatabase.getContainer(containerName); setupRoundTripContainer(); List<Map<String, Object>> keyValuePropsList = new ArrayList<>(); Map<String, Object> props; boolean flag = false; final int initialDocumentsSize = 30; for(int i = 0; i < initialDocumentsSize; i++) { props = new HashMap<>(); props.put("propInt", i); props.put("propStr", String.valueOf(i)); List<Integer> orderByArray = new ArrayList<Integer>(); Map<String, String> orderByObject = new HashMap<>(); for (int k = 0; k < 3; k++) { orderByArray.add(k + i); orderByObject.put("key1", String.valueOf(i)); orderByObject.put("key2", String.valueOf(orderByArray.get(k))); } props.put("propArray", orderByArray); props.put("propObject", orderByObject); switch (i % 8) { case 0: props.put(PROP_MIXED, i); props.put(PROPTYPE, "number"); break; case 1: props.put(PROP_MIXED, String.valueOf(i)); props.put(PROPTYPE, "string"); break; case 2: props.put(PROP_MIXED, orderByArray); props.put(PROPTYPE, "array"); break; case 3: props.put(PROP_MIXED, orderByObject); props.put(PROPTYPE, "object"); break; case 4: props.put(PROP_MIXED, (float)i*3.17); props.put(PROPTYPE, "number"); break; case 5: props.put(PROP_MIXED, null); props.put(PROPTYPE, "null"); break; case 6: flag = !flag; props.put(PROP_MIXED, flag); props.put(PROPTYPE, "boolean"); break; default: break; } keyValuePropsList.add(props); } props = new HashMap<>(); keyValuePropsList.add(props); createdDocuments = bulkInsert(createdCollection, keyValuePropsList); for(int i = 0; i < 10; i++) { Map<String, Object> p = new HashMap<>(); p.put("propScopedPartitionInt", i); InternalObjectNode doc = getDocumentDefinition("duplicatePartitionKeyValue", UUID.randomUUID().toString(), p); createdDocuments.add(createDocument(createdCollection, doc)); } numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) .readPartitionKeyRanges("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), (CosmosQueryRequestOptions) null) .flatMap(p -> Flux.fromIterable(p.getResults())).collectList().single().block().size(); waitIfNeededForReplicasToCatchUp(getClientBuilder()); updateCollectionIndex(); } private void setupRoundTripContainer() { String pk = "pk1"; for (int i = 0; i < 15; i++) { RoundTripDocument doc; if (i < 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 3); } else if (i == 13) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } roundTripsContainer.createItem(doc).block(); } pk = "pk2"; for (int i = 0; i < 10; i++) { RoundTripDocument doc; if (i < 1) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 3) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 8) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } pk = "pk3"; for (int i = 0; i < 11; i++) { RoundTripDocument doc; if (i < 2) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 4); } else if (i < 5){ doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 5); } else if (i < 7) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 6); } else if (i < 9) { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 7); } else { doc = new RoundTripDocument(UUID.randomUUID().toString(), pk, "testing", 8); } roundTripsContainer.createItem(doc).block(); } } @Test(groups = { "query" }, timeOut = TIMEOUT) public void queryDocumentsValidateContentWithObjectNode() throws Exception { InternalObjectNode expectedDocument = createdDocuments .stream() .filter(d -> d.getMap().containsKey("propInt")) .min(Comparator.comparing(o -> String.valueOf(o.get("propInt")))).get(); String query = String.format("SELECT * from root r where r.propInt = %d ORDER BY r.propInt ASC" , expectedDocument.getInt("propInt")); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); CosmosPagedFlux<ObjectNode> queryObservable = createdCollection.queryItems(query, options, ObjectNode.class); List<String> expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); Map<String, ResourceValidator<InternalObjectNode>> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), new ResourceValidator.Builder<InternalObjectNode>().areEqual(expectedDocument).build()); FeedResponseListValidator<InternalObjectNode> validator = new FeedResponseListValidator.Builder<InternalObjectNode>() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .allPagesSatisfy(new FeedResponseValidator.Builder<InternalObjectNode>().hasRequestChargeHeader().build()) .hasValidQueryMetrics(true) .build(); validateQuerySuccess(queryObservable.byPage().map(response -> ImplementationBridgeHelpers .FeedResponseHelper .getFeedResponseAccessor() .convertGenericType( response, objectNode -> new InternalObjectNode(objectNode) )), validator); } private void updateCollectionIndex() { CosmosContainerProperties containerProperties = createdCollection.read().block().getProperties(); IndexingPolicy indexingPolicy = containerProperties.getIndexingPolicy(); List<IncludedPath> includedPaths = indexingPolicy.getIncludedPaths(); IncludedPath includedPath = new IncludedPath("/propMixed/?"); if (!includedPaths.contains(includedPath)) { includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); containerProperties.setIndexingPolicy(indexingPolicy); createdCollection.replace(containerProperties).block(); } } @AfterClass(groups = { "query" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private void assertInvalidContinuationToken(String query, int[] pageSize, List<String> expectedIds) { String requestContinuation = null; do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken( new CompositeContinuationToken( "asdf", new Range<String>("A", "D", false, true)), new QueryItem[] {new QueryItem("{\"item\" : 42}")}, "rid", false); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(orderByContinuationToken.toString(),1).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertError(CosmosException.class); } while (requestContinuation != null); } private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List<String> expectedIds) { for (int pageSize : pageSizes) { List<InternalObjectNode> receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List<String> actualIds = new ArrayList<String>(); for (InternalObjectNode document : receivedDocuments) { actualIds.add(document.getResourceId()); } assertThat(actualIds).containsExactlyElementsOf(expectedIds); } } private List<InternalObjectNode> queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List<String> continuationTokens = new ArrayList<String>(); List<InternalObjectNode> receivedDocuments = new ArrayList<InternalObjectNode>(); do { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<InternalObjectNode> queryObservable = createdCollection.queryItems(query, options, InternalObjectNode.class); TestSubscriber<FeedResponse<InternalObjectNode>> testSubscriber = new TestSubscriber<>(); queryObservable.byPage(requestContinuation, pageSize).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); @SuppressWarnings("unchecked") FeedResponse<InternalObjectNode> firstPage = (FeedResponse<InternalObjectNode>) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); return receivedDocuments; } private static InternalObjectNode getDocumentDefinition(String partitionKey, String id, Map<String, Object> keyValuePair) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); for(String key: keyValuePair.keySet()) { Object val = keyValuePair.get(key); sb.append(" "); sb.append("\"").append(key).append("\"").append(" :" ); if (val == null) { sb.append("null"); } else { sb.append(toJson(val)); } sb.append(",\n"); } sb.append(String.format(" \"id\": \"%s\",\n", id)); sb.append(String.format(" \"mypk\": \"%s\"\n", partitionKey)); sb.append("}"); return new InternalObjectNode(sb.toString()); } private static InternalObjectNode getDocumentDefinition(Map<String, Object> keyValuePair) { String uuid = UUID.randomUUID().toString(); return getDocumentDefinition(uuid, uuid, keyValuePair); } private static String toJson(Object object){ try { return Utils.getSimpleObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } static class RoundTripDocument { @JsonProperty("id") String id; @JsonProperty("mypk") String pk; @JsonProperty("type") String type; @JsonProperty("v") int v; public RoundTripDocument(String id, String pk, String type, int v) { this.id = id; this.pk = pk; this.type = type; this.v = v; } public RoundTripDocument() { } public String getId() { return id; } } }
If we think this will be a hot path, could make a check for `exp instanceof long` before calling `toString` and `Long.parseLong` on it
public static OffsetDateTime retrieveExpiration(String jwtValue) { if (CoreUtils.isNullOrEmpty(jwtValue)) { throw new IllegalArgumentException("Value cannot be null or empty: 'jwtValue'."); } String[] jwtParts = jwtValue.split("[.]"); if (jwtParts.length < 2) { return null; } String jwtPayloadEncoded = jwtParts[1]; if (CoreUtils.isNullOrEmpty(jwtPayloadEncoded)) { return null; } byte[] jwtPayloadDecodedData = Base64.getDecoder().decode(jwtPayloadEncoded); try (JsonReader jsonReader = JsonProviders.createReader(jwtPayloadDecodedData)) { Map<String, Object> jsonTree = jsonReader.readMap(JsonReader::readUntyped); Object exp = jsonTree.get("exp"); if (exp == null) { return null; } else { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(exp.toString())), ZoneOffset.UTC); } } catch (IOException exception) { return null; } }
}
public static OffsetDateTime retrieveExpiration(String jwtValue) { if (CoreUtils.isNullOrEmpty(jwtValue)) { throw new IllegalArgumentException("Value cannot be null or empty: 'jwtValue'."); } String[] jwtParts = jwtValue.split("[.]"); if (jwtParts.length < 2) { return null; } String jwtPayloadEncoded = jwtParts[1]; if (CoreUtils.isNullOrEmpty(jwtPayloadEncoded)) { return null; } byte[] jwtPayloadDecodedData = Base64.getDecoder().decode(jwtPayloadEncoded); try (JsonReader jsonReader = JsonProviders.createReader(jwtPayloadDecodedData)) { Map<String, Object> jsonTree = jsonReader.readMap(JsonReader::readUntyped); Object exp = jsonTree.get("exp"); if (exp == null) { return null; } else { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(exp.toString())), ZoneOffset.UTC); } } catch (IOException exception) { return null; } }
class JsonWebToken { /** * Retrieves the expiration date from the specified JWT value. * * @param jwtValue The JWT value. * @return The date the JWT expires or null if the expiration couldn't be retrieved. * @throws IllegalArgumentException If the {@code jwtValue} is null or empty. */ }
class JsonWebToken { /** * Retrieves the expiration date from the specified JWT value. * * @param jwtValue The JWT value. * @return The date the JWT expires or null if the expiration couldn't be retrieved. * @throws IllegalArgumentException If the {@code jwtValue} is null or empty. */ }
For some reason, `readUntyped()` was creating exp as a `String`, causing a `ClassCastException` when attempting to cast top `long` directly.
public static OffsetDateTime retrieveExpiration(String jwtValue) { if (CoreUtils.isNullOrEmpty(jwtValue)) { throw new IllegalArgumentException("Value cannot be null or empty: 'jwtValue'."); } String[] jwtParts = jwtValue.split("[.]"); if (jwtParts.length < 2) { return null; } String jwtPayloadEncoded = jwtParts[1]; if (CoreUtils.isNullOrEmpty(jwtPayloadEncoded)) { return null; } byte[] jwtPayloadDecodedData = Base64.getDecoder().decode(jwtPayloadEncoded); try (JsonReader jsonReader = JsonProviders.createReader(jwtPayloadDecodedData)) { Map<String, Object> jsonTree = jsonReader.readMap(JsonReader::readUntyped); Object exp = jsonTree.get("exp"); if (exp == null) { return null; } else { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(exp.toString())), ZoneOffset.UTC); } } catch (IOException exception) { return null; } }
}
public static OffsetDateTime retrieveExpiration(String jwtValue) { if (CoreUtils.isNullOrEmpty(jwtValue)) { throw new IllegalArgumentException("Value cannot be null or empty: 'jwtValue'."); } String[] jwtParts = jwtValue.split("[.]"); if (jwtParts.length < 2) { return null; } String jwtPayloadEncoded = jwtParts[1]; if (CoreUtils.isNullOrEmpty(jwtPayloadEncoded)) { return null; } byte[] jwtPayloadDecodedData = Base64.getDecoder().decode(jwtPayloadEncoded); try (JsonReader jsonReader = JsonProviders.createReader(jwtPayloadDecodedData)) { Map<String, Object> jsonTree = jsonReader.readMap(JsonReader::readUntyped); Object exp = jsonTree.get("exp"); if (exp == null) { return null; } else { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(exp.toString())), ZoneOffset.UTC); } } catch (IOException exception) { return null; } }
class JsonWebToken { /** * Retrieves the expiration date from the specified JWT value. * * @param jwtValue The JWT value. * @return The date the JWT expires or null if the expiration couldn't be retrieved. * @throws IllegalArgumentException If the {@code jwtValue} is null or empty. */ }
class JsonWebToken { /** * Retrieves the expiration date from the specified JWT value. * * @param jwtValue The JWT value. * @return The date the JWT expires or null if the expiration couldn't be retrieved. * @throws IllegalArgumentException If the {@code jwtValue} is null or empty. */ }